I have a website that utilizes AJAX to fetch data in JSON format from the backend and then displays it on the page. The website is built using MVC .NET framework.
Below is the function responsible for loading events from the backend:
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 purposely cause the request to fail (by changing the URL), it triggers the error: function(data)
, leading to the successful loading of the hardcoded JSON object. Subsequently, it enters the 'complete: function(data)' section and adds the events one by one.
However, when I use the correct URL and retrieve events from the backend, it appears they arrive too late - just as it exits the complete
section. This raises the question: Why does this occur? My understanding was that complete
executes once the response is received. Am I mistaken in assuming this? How can I rectify this issue so that the events are loaded from the backend and displayed on the page seamlessly?
Thank you!