I'm facing a problem where for some reason the flow of my app is asynchronous and doesn't go according to expectations. Maybe I'm misunderstanding Ajax, could someone advise me how to structure my flow properly:
I have a document.onReady()
block of code where I define what happens on startup. On startup I need to load a bunch of data from the DB, which is an Ajax call to the server.
$(document).ready(function() {
// ... some GUI startup steps go here ...
// Now, I also need to pre-load a DB fetch in my app
var activities = ajaxGetActivities();
// ... Do something with 'activities' here
parseActivities(activities);
}
AJAX method ajaxGetActivities() (no issues here, it returns the right thing)
function ajaxGetActivities() {
$.ajax({
type : "post",
dataType : "json",
url : '/myapp/activityFetch.mvc',
data : '', // no data
success : function(data) {
var result = otherAjaxProcessing(data); // this is OK, it works
return result; // returns the right result, OK
},
error : function(data) {
alert('System Error, data: ' + data);
return null;
}
});
}
What's happening is the debugger immediately drops to the next line in Snippet #1, parseActivities()
, but at that time the variable activities
is NULL. I assume the Ajax call hasn't started or completed yet. At some point later on, I hit my breakpoint inside the Ajax call, but it's sort of useless now because the flow has already gone on to the next steps in document.onReady
where my activities variable is NULL!
Somehow I'm not synchronizing the result of the DB Fetch with the next steps in document.onReady
that require it. I verified that I'm returning the right thing from the Ajax method, but document.onReady
never picks it up.