0

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>
sparkle
  • 7,530
  • 22
  • 69
  • 131
  • Please search for "jquery return value from ajax". The answer will be there. –  May 04 '12 at 21:41
  • http://stackoverflow.com/questions/2960417/getjson-and-variable-scope-in-javascript , http://stackoverflow.com/questions/4158865/javascript-global-variable-problem , http://stackoverflow.com/questions/3537434/cant-get-correct-return-value-from-an-jquery-ajax-call –  May 04 '12 at 21:45
  • possible duplicate of [How can I return a variable from a $.getJSON function](http://stackoverflow.com/questions/31129/how-can-i-return-a-variable-from-a-getjson-function) –  May 04 '12 at 21:46

2 Answers2

3

Change it to:

$.getJSON('list.json', function(data) {
  $.each(data['pranks'], function(key, val) {
    pranks.push(val);
  });
  alert(pranks.length); /* pranks has data now */
});
Tim B James
  • 20,084
  • 4
  • 73
  • 103
1

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.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116