Can I interact with XML after Jquery $.ajax() has executed? – Education Career Blog

Is it possible to interact with an XML file after making a $.ajax() call?

IE:

.$ajax( 
url: "someUrl", 
type: "GET", 
dataType:"xml", 
success: function(xml){ //some function },
error : function(){ //some function}
});

$("#somebutton").click(function(xml){ //function that interacts with XML });

I haven’t been able to interact with any XML file’s unless all the functions are inside the success parameter. Any tips, or do I just need to put all my functions into the success function? Is there a better way to do what I’m describing than using $.ajax()

,

the success function is a closure that executes when a response has come back from the server. The variable, xml is only valid within the scope of the function. What you CAN do is a few things:

  1. put your handlers into the success
    function
  2. create a variable OUTSIDE of the ajax call, and in the success
    function assign the value of XML to
    that variable

so:

var xmlObj = "";
$.ajax({
  success:function(xml) {
    xmlObj = xml;
  }
});

alert(xmlObj);

,

The functions don’t have to be in the success function to use it, but the xml varible only exists inside the success functions scope you would have to set another variable to it.

Doesn’t work

$.ajax( 
  url: "someUrl", 
  type: "GET", 
  dataType:"xml", 
  success: function(xml){ //some code },
  error : function(){ //some code}
});

function parse() {
  //xml processing code
}

Works

var myXML;

$.ajax( 
  url: "someUrl", 
  type: "GET", 
  dataType:"xml", 
  success: function(xml){ 
    myXML = xml;
    //some code 
  },
  error : function(){ //some code}
});

function parse() {
  //myXML processing code
}

Also if you would call parse before the AJAX call has completed successfully, then the myXML variable would still be null. Could always perform a check.

function parse() {
  if (myXML) {
    //myXML processing code
  } else {
    //ajax not completed successfully yet
  }
}

,

You can also do it this way which doesn’t require global variables:

$.ajax({ 
    url: "someUrl", 
    type: "GET",
    dataType:"xml", 
    success: function(xml){
        $("#somebutton").bind("click",{xmlData:xml}, buttonClick);
    },
    error : function(){ /*some code*/ }
});

function buttonClick(event) {
    var xml = event.data.xmlData;
    //function that interacts with XML
}

Leave a Comment