I have two nested ajax calls to server.
In 1st ajax call, server returns me the XML which contain ordered list of objects, server order the list by date ascending order. Here, I do get objects in date’s ascending order.
In the second ajax call’s success function, I simply output the dates of objects, but my objects are suddenly surprisingly not in date’s ascending order, why?
My code looks like below (please don’t feel confused about my two ajax calls, I explained them after the code):
$.ajax({
type : "GET",
url : MY_URL_1,
dataType : "xml",
success : function(xml) {
$(xml).find("DOCUMENT").each(function() {
var eachXMLdata = $(this);
var date = eachXMLdata.children("DATE").text();
// I successfully get the date in ascending order
console.log('date:'+date);
$.ajax({
type : "GET",
url : MY_URL_2,
dataType : "xml",
success : function(xml) {
var date = eachXMLdata.children("DATE").text();
//I have not change anything of eachXMLdata,
//why the order of the dates get messed up here
console.log('date:'+date);
}//end of 2nd ajax success function
});// end of 2nd ajax call
});//end of "each" function
}//end of 1st ajax success function
});//end of 1st ajax call
As you saw above, there are two nested ajax calls, that’s the second ajax call is inside first ajax call’s success function (and in the "each" function).
In the first ajax call, I console output the date of each object, which is correctly showing in ascending order.
The strange problem comes after I output the objects’ date again in the second ajax call’s success function, the dates are no longer in ascending order, why? I have not change anything of eachXMLdata, why two console outputs give me different order of the dates? and how to get rid of it?
I finally get rid of the problem by set “
async: false” for the inner ajax call. This is the root cause.