Shrout1
Shrout1

Reputation: 2607

JQuery AJAX return XML on GET request complete

I need to execute code once my XML file (or object) has been returned successfully. Not before, and not repeatedly; just one time after the file has been returned.

Does my code already do what I am trying to accomplish? It seems to have failed a couple of times in IE and I need to be sure that it is reliable.

$(document).ready(function(){
    (function GetFile(){
        $.ajax({
          type: "GET",
          url: "Produce.xml",
          dataType: "xml",
          cache: false,
          success: function(result) {
                alert("XML File is loaded!");
                alert(result);
                },      
            async: true
          });
    })();
});

I know that there are onerror codes and readystatechange values that can be checked and verified... Should I be checking these values while polling the server for the XML file?

Upvotes: 0

Views: 11774

Answers (2)

durron597
durron597

Reputation: 32323

This was added as an edit by the original asker, I have converted it to a community wiki answer because it should be an answer, not an edit.

Fixed it thanks to @AndrewDouglas suggestion and here is the new code (which works great):

$(document).ready(function(){
(function GetFile(){
    $.ajax({
      type: "GET",
      url: "Produce.xml",
      dataType: "xml",
      cache: false,
      success: function(result) {
            alert("XML File is loaded!");
            alert(result);
        },
      error:function (xhr, ajaxOptions, thrownError){
            z++;
            alert(xhr.status);
            alert(thrownError);
            setTimeout(GetFile, 5000);
            console.log("Error " +z+": " + thrownError);
        },              
            async: true
        });
    })();
});

One final comment, you should be able to change setTimeout(GetFile, 5000) to setInterval(GetFile, 5000) and then it will continually poll your XML file. Doing that in the success section would make a bit more sense, however.

Upvotes: 0

user554180
user554180

Reputation:

remove comma after async: true

Also, your GetFile function will execute immediately if you're not planning on calling again then might as well go with anonymous or remove that function all together

$(document).ready(function(){
        $.ajax({
          type: "GET",
          url: "Produce.xml",
          dataType: "xml",
          cache: false,
          success: function(result) {
                alert("XML File is loaded!");
                alert(result);
                },      
            async: true
          });
});

Upvotes: 1

Related Questions