user3010406 user3010406 - 3 years ago 146
Ajax Question

Ajax call in Ajax Call, First One Always completes?

I have an ajax call, that based on the return, calls another ajax call by effecting its url parameter, the url being modified by the return of the first. These two calls are related, because the first feeds the url parameter of the second, and its output is appended to a global variable which is used to generate a final set of HTML, subsequently appended in the first call. As a simplified example:



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var masterHtml = '';

$.ajax({
url: "http://thisisanexample/items",
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandler(data);
},
error: function (data) {

}
});

function successHandler(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someHtml = results[i]["someHtml"];
masterHtml = masterHtml + someHtml;
var nextThingUrl = results[i]["nextThingUrl"];
// now go get the other HTML, and append it to the masterHtml,
//this is a series of child elements to the someHtml variable above
$.ajax({
url: "http://thisisanexample/+ " + nextThingUrl,
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
successHandlerChildren(data);
},
error: function (data) {

}
});
jQuery('#magictime').append(masterHtml);
}
}

function successHandlerChildren(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var someMoreHtml = results[i]["someMoreHtml"];
masterHtml = masterHtml + someMoreHtml;
}
}





My problem is the first ajax call always completes all the way before the second call is issued so I get the first set of HTML, while the second call provides some HTML I need. This messes up the order of operations. What am I missing? TIA!!!

Answer Source

The option for async is spelled wrong, correct is:

async: false

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download