I have a webpage which when it is loaded makes an ajax request to get some data in JSON [] format from the back end and display it on the page. The webpage is generated with MVC .NET
The function that loads the events from the back end:
function initEvents() {
$.ajax({
url: '/Work/GetEvents/' + id, type: "GET", dataType: 'json',
success: function (data) {
events = data;
},
error: function(data) {
// Note: hardcoded JSON event in here
events = hardcodedEvents;
},
complete: function(data) {
// Add events
for (var i = 0; i < events.length; i++){
addEvent(events[i]);
}
}
});
}
When I make the request fail (ie change the url to point to bogus data) – it goes in error: function(data) – so the hardcoded JSON object loads fine then it goes in the ‘complete: function(data)` and adds the events 1 by 1.
However, when I use the correct URL and get the events from the backend, it seems the events arrive too late; just as it exits the complete section. The question is: Why is this happening? I thought complete loaded whenever the reply came back. Am I wrong to believe this? How can I fix this so the events are loaded from the back end and into the page?
Thanks!
eventsis not defined in the scope of thecompleteevent. You should pass theeventsdata to another function, or simply move theaddEventlogic to within the event handler. eg:Note that
completeis called when the request finishes (after success and error callbacks are executed). Since you only want to run your handler once per request, you shouldn’t use it in this case.