1

This is the code I currently have. What I want to do is get change the array in xmlParser and return it to main (ready function) to use it for all other functions. However, as far as I can see, the $("#text") will run before the array is returned. Is there anyway to delay this?

$(document).ready(function() {
    var infoArray = []
    $.ajax({
        type: "GET",
        url: "works.xml",
        dataType: "xml",
        success: function(xml) { infoArray = xmlParser(xml)}
    });
    $("#test").text(infoArray.length);
});

function xmlParser (xml) {
    //do some push
    //I have a test here to make sure that the length of the array is what I want
    return Array;
}
Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37
  • 1
    ajax is async. move $("#test").text(infoArray.length) to the function(xml) body – gidim Oct 27 '15 at 02:28
  • Move it inside the success function, so it only runs once the ajax has returned. – Coz Oct 27 '15 at 02:29
  • Possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Dave Oct 27 '15 at 02:43

2 Answers2

2

Your Ajax call is asynchronous. That means it starts when you execute it here and it finishes sometime later. You must put any code that uses the result of the ajax call inside the success handler or in a function that you call from the success handler and pass the data to.

An asynchronous operation in Javascript finishes at some future indeterminate time. Meanwhile, the following lines of code continue to execute (before the Ajax code finishes). Then, sometime LATER, after the current thread of execution is done and when the result comes back from the server that the Ajax call was sent to, the success handler for the Ajax call is called and that code executes.

Here's how you consume the result of the ajax call inside the success handler:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "works.xml",
        dataType: "xml",
        success: function(xml) { 
            var infoArray = xmlParser(xml)
            $("#test").text(infoArray.length);
        }
    });
});

function xmlParser (xml) {
    //do some push
    //I have a test here to make sure that the length of the array is what I want
    return Array;
}

In case you didn't know, the first "A" in "Ajax" stands for Asynchronous.


FYI, it is worth learning how to use promises for asynchronous operations. jQuery automatically builds promises for its ajax operations so you can execute the above code using promises like this:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "works.xml",
        dataType: "xml"
        }
    }).then(function(xml) {
        var infoArray = xmlParser(xml)
        $("#test").text(infoArray.length);
    }, function(err) {
        // handle errors here
    });
});

It doesn't look a whole lot better here, but if you start sequencing multiple asynchronous operations or have nested asynchronous operations or want to wait until multiple asynchronous operations are done, promises can make all that a whole lot simpler.

And, promises are built into ES6 so you will see more and more code using them over time.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks for explaining what is asynchronous is. I am having struggling with what it will do!!! – Tree Nguyen Oct 27 '15 at 02:32
  • 2
    @TreeNguyen - If you're going to be doing Ajax calls from the browser, you will want to get very familiar with how to use asynchronous results in Javascript because it is the way of Javascript and Ajax. It isn't really that complicated a concept once someone explains it to you, but it does mean you have to code sequences of operations differently. You can't code them linearly like regular synchronous operations. Instead, you have to "continue" the next step in the success handler. Promises provide a more streamlined way of managing async operations, but they are one more thing to learn. – jfriend00 Oct 27 '15 at 02:35
  • @jfriend00 can ask about ajax since this an ajax related question. i always use ajax for every transaction i do with the database . i do it to creat,retrieve,update,delete data. is there a drawback of using so much ajax in webpage? – guradio Oct 27 '15 at 02:47
  • 1
    @Pekka - no drawback to using lots of ajax. It's the main way that Javascript in a web page communicates with a server if you don't want to post a form and load a new page. – jfriend00 Oct 27 '15 at 02:48
  • When i post my comment the update wasnt available so i am going to ask about the promise since i havent used it yet and i sort of didnt understand the explanation.is promise different from success part of ajax?in the sample there is no success part. only then part. what would happened if it fails?i always use this format `$.ajax({}, success: function(data) {} }, error: function(data) {} });` @jfriend00 – guradio Oct 27 '15 at 02:51
  • @Pekka - the `.then()` method accepts an optional second callback function which is the failure handler. It is explained [here on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) and in pretty much every online resource about using promises. – jfriend00 Oct 27 '15 at 03:24
  • Hi. I have just looked around and decided to use done() for my code. However, that error keep popping up. Can you have a look for me @jfriend00 ? – Tree Nguyen Oct 27 '15 at 08:29
  • @TreeNguyen - please don't use `.done()`. `.then()` is the ES6 standard. `.done()` is a jQuery proprietary. jQuery supports `.then()`. Have a look at what? – jfriend00 Oct 27 '15 at 08:31
1

Put $("#test").text(infoArray.length); inside the success function.

Justice
  • 290
  • 2
  • 7