I have simple JavaScript code that is using the Ajax API for fetching a XML from the server.
function loadXML(path, node) {
var response_obj = "";
/* Fire Ajax request and get the XML */
var request_obj = "";
$.ajax({
async: true,
type: "GET",
url: path,
dataType: "xml",
success: function(XMLObj, status, resquestObj) {
response_obj = XMLObj;
request_obj = requestObj;
},
error: function(){
alert("Unable to fire AJAX request");
}
});
alert(response_obj); //<-- This is NULL if async=true
/* More logic to follow which will use response_obj (XML)
and render it in the 'node' argument passed. */
}
Where, the path corresponds to a valid XML (tested using W3C validator) and the node points to a DIV element on the HTML page where the response has to be parsed and appended.
What I need is that the Ajax call should return me the responseXML object which I will parse and render. For that, I am assigning the response XML to a local variable (local to this function’s scope) and then would use it (currently I just send it to alert).
Now, the problem is that when I use this function with async set to false, the alert call successfully returns [object XMLDocument]. But as soon as I change async to true, null is printed by alert.
What I understand is that when async:true, the last alert is called even before the XML is returned by the Ajax call. Similarly, when async:false, this is a serialized call and when control reaches the last alert call, the XML has already arrived.
What should I do so that:
- I have the response Object (and
request object) as returned by the Ajax
call in the local variables so that
I can use them. I understand that
the call back function, if passed to
success, would have three
parameters – but, I don’t know how
to return from that call back
function into myloadXMLfunction. - That I don’t have to convert the Ajax call into sync because this is just one of the functions that I am firing – there are many other Ajax calls which too are to be issued.
- Am I correct in my assumption that
async:falseis serialized in this function whereasasync:trueis not?
yes, what you have mentioned about
async:trueis correct. So it’s natural thatalert()will fail if async is true and if async is false it will work.You should put the
alert()in the success callback.Or you can also make a function say
ajaxSuccessand call it in successCallback().Put the
alert()in thatajaxSuccessfunction.