sparkle
sparkle

Reputation: 7400

Global variable in JavaScript not set when using getJSON?

Here's my code. If i check "pranks" variable by "google inspector" all works fine. But the "alert" on the last line show a 0-size array! I mucking with local/global variables?

<script type="text/javascript">
(function() { 

 pranks = [];

function getAllPranks(){


    $.getJSON('list.json', function(data) {

      $.each(data['pranks'], function(key, val) {
        pranks.push(val);
      });

    });

}

 $(document).ready(function(){


    getAllPranks();

    alert(pranks.length);

 });


 }());
 </script>

Upvotes: 0

Views: 1564

Answers (2)

Florian Margaine
Florian Margaine

Reputation: 60747

Taking your code:

<script type="text/javascript">
(function() { 
    function getAllPranks( callback ) {
        $.getJSON('list.json', function(data) {
            $.each(data['pranks'], function(key, val) {
                pranks.push(val);
            });
            callback( pranks );
        });
    }

    $(document).ready(function(){
        getAllPranks( function( pranks ) {
            alert(pranks.length);
        } );
    });
}());
</script>

$.getJSON is asynchronous. This means the callback function (function(data)) is executed once the result comes back. When you execute alert(pranks.length), the function has not executed because the response hasn't come back at this moment.

Upvotes: 1

Tim B James
Tim B James

Reputation: 20364

Change it to:

$.getJSON('list.json', function(data) {
  $.each(data['pranks'], function(key, val) {
    pranks.push(val);
  });
  alert(pranks.length); /* pranks has data now */
});

Upvotes: 3

Related Questions