0

i have a global variable images, which is filled with path-names, coming from an xml file. The function that parses the xml-file works, and fills the array. But when the function is finished, my global variable is still empty. Does someone have a solution?

$(document).ready(function() {
var images = [];
var descriptions = [];
getImages();


function getImages() {
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "xml/page_pictures.xml",
            dataType: "xml",
            success: xmlParser
        });
    });

    function xmlParser(xml) {
        $(xml).find("pages").children().each(function() {               
                $(this).find("images").children().each(function() { //find all the image nodes in this node
                    images.push($(this).attr("path").toString());
                    descriptions.push($(this).find("image-label").text());              
                });
            });
        }
}


});

When debugging, i notice that at the end of the .each, my variable images is filled with 129 items, but when the function is completely finished and i check "images" after the getImages(), my variable "images" is empty again

Thanks in advance.

  • `$.ajax` is **A**synchronous which means that when `getImages` ends, `xmlParser` has not run yet. – Andrew Whitaker Jan 09 '14 at 13:48
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Ram Jan 09 '14 at 13:50
  • To take the comments a step further -- any immediate access to `images` needs to be done inside of your callback (`xmlParser`). I wouldn't suggest it but you can supply `async: false` in the `$.ajax` callback if you really need synchronous behavior. – ach Jan 09 '14 at 13:50

0 Answers0