0

I am trying to parse a simple XML file,

<gallery>
    <photo><file>Image1</file></photo>
    <photo><file>Image2</file></photo>
    <photo><file>Image3</file></photo>
<gallery>

then execute a callback function. The parsing works fine, but I cannot get the callback to fire after the parse. I am trying to obtain

Image1
Image2
Image3
Done!

but Done! is always being output before the images can be listed. Why is this? Here is my Jquery code:

$(document).ready(function(){ 
    var imgArray=[];

    function xmlparse(callback){
    $.get("gallery.xml",{},function(xml){
    $('photo',xml).each(function(i){
        file = $(this).find("file").text();
        (imgArray).push(file);
            $('.content').append(imgArray[i] + '<br>'); 
        i++;
    });
    });
    if(typeof callback == "function") callback();
    };

    xmlparse(function(){
    $('.content').append('Done! <br>');
});
});

Is a delay timer necessary or are there ways to use .done, .resolve, and so forth?

1 Answers1

0

this should work, also take a look at the resolve() function.

$(document).ready(function(){ 

var imgArray=[];
function xmlparse(){
$.get("gallery.xml",{},function(xml){
     $('photo',xml).each(function(i){
        file = $(this).find("file").text();
         (imgArray).push(file);
         $('.content').append(imgArray[i] + '<br>'); 
         i++;
     }).promise().done( function(){ 
            $('.content').append('Done! <br>'); });
     });

xmlparse();

});

best

M

mboeckle
  • 938
  • 13
  • 29
  • Mboeckle, you are the freakin' man. My Smashing jQuery book doesn't get this advanced, and I thought .promise was just for animation. Thanks mucho! Though I am still curious... if xmlparse() wasn't a parser but an internal function, my callback worked. Is it because of the delay having to access another file? – Chris Niestepski Jun 14 '14 at 02:31
  • Yes please accept the answer - you load the file through $get and just attach .promise to the $each loop; try adding .done to the $get should work to or . complete (also if its not successfull but done) you can add the each loop there inside – mboeckle Jun 14 '14 at 09:01