Skip to main content
added 31 characters in body
Source Link
Josiah Ruddell
  • 29.9k
  • 8
  • 67
  • 68

It can help to visualize the code like this.

    var icon; 
    $(function(){
        $.get('data.xml', callback); // sends ajax request
        // next line happens immediately unless ajax request is set to synchronous
        console.log(icon); // logs undefined
    });
    function callback(xml){ // onsuccess callback happens
        icon = xml.documentElement.getElementsByTagName("icon");
        console.log(icon); // logs Array
    }

I removed the anonymous function and placed the callback after the console.log. Like others have pointed out the ajax callback happens asynchronously, while javascript continues to execute.

It can help to visualize the code like this.

    var icon; 
    $(function(){
        $.get('data.xml', callback); // sends ajax request
        // next line happens immediately unless ajax request is set to synchronous
        console.log(icon); 
    });
    function callback(xml){ // onsuccess callback happens
        icon = xml.documentElement.getElementsByTagName("icon");
        console.log(icon);
    }

I removed the anonymous function and placed the callback after the console.log. Like others have pointed out the ajax callback happens asynchronously, while javascript continues to execute.

It can help to visualize the code like this.

    var icon; 
    $(function(){
        $.get('data.xml', callback); // sends ajax request
        // next line happens immediately unless ajax request is set to synchronous
        console.log(icon); // logs undefined
    });
    function callback(xml){ // onsuccess callback happens
        icon = xml.documentElement.getElementsByTagName("icon");
        console.log(icon); // logs Array
    }

I removed the anonymous function and placed the callback after the console.log. Like others have pointed out the ajax callback happens asynchronously, while javascript continues to execute.

Source Link
Josiah Ruddell
  • 29.9k
  • 8
  • 67
  • 68

It can help to visualize the code like this.

    var icon; 
    $(function(){
        $.get('data.xml', callback); // sends ajax request
        // next line happens immediately unless ajax request is set to synchronous
        console.log(icon); 
    });
    function callback(xml){ // onsuccess callback happens
        icon = xml.documentElement.getElementsByTagName("icon");
        console.log(icon);
    }

I removed the anonymous function and placed the callback after the console.log. Like others have pointed out the ajax callback happens asynchronously, while javascript continues to execute.