My function below makes and AJAX call and since it is an invalid JSON object returned I have to manually parse the results into a valid JSON object (which works). The problem is when I am passing the JSON object back to the original calling function the object doesn’t get passed back correctly.
If I only put the third alert in it will say ‘invalid’ for the object. However if I put all three alerts in, only alert 2 will say invalid (1 and 3 will show object). This makes believe it might be some type of timing issue passing the object between these variables. Any recommendations on how to resolve this, as I obviously cannot put alerts in my final code.
function loadDocuments(){
var myDocuments = getDocs();
alert('third response ' + myDocuments);
}
function getDocs() {
var myURL = "someURL";
var response;
$.ajax({
url: myURL,
type: 'GET',
dataType: 'json',
complete: function(docData) {
if(docData.status==200){
response = parseDocResults(docData.responseText);
alert('first response' + response);
}else{
response = "Documents failed to load";
}
}
});
alert('second response' + response);
return response;
}
Using AJAX the way you tried it means using it in a
synchronousapproach which blocks the browser until the transfer is finished. You can find anasyncconfiguration flag for the$.ajax()function which makes the AJAX work synchronous when set tofalsebut I wouldn’t recommend it (and it’s deprecated too).The
$.ajax()function just sends an HTTP request towards the server. It does not wait for a reply it returns immediately and execution continues with what ever instructions were after the ajax function call.Sometime later the browser (JavaScript) receives an HTTP response from the server. Your ajax function call specified a
complete/successcallback which is used to handle the HTTP response. But since that callback was executed “sometime later” you have to shape your logic from within the callback, without relying on a return value.