views:

17

answers:

1

Hi All,

I have a simple javascript using 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 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.

Can someone please suggest me what should I do so that:

  1. I have the response Object (and request object) as returned by 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 my loadXML function.
  2. That I don't have to convert the AJAX call into sync because this is just one the functions that I am firing - there are many other AJAX calls which too are to be issued.
  3. Am I correct in my assumption that async:false is serialized in this function where as async:true is not?

[I hope I am able to frame the question properly.]

Thanks a lot in advance. Shrey

+1  A: 

Ya what you have mentioned about async:true is right. So Its natural that alert() 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 ajaxSuccess and call it in success Callback(). Put the alert() in that ajaxSuccess function

Thanks for reply. Actually, which ever function gets the XML, also needs the HTML 'node' - so, my problem is what should I do so that the callback has the node also. (I apologize in case this was not implicit in the question text). Thanks anyways, for confirming my understanding.
Shrey