-2

I'm new in the web programming and I don't fully understand some simple things. Suppose we have following ajax request:

var records = [];
   $.ajax(
   {
        url : "index", 
        dataType: 'json',
        success: function (response)
        {
           records = response;
        }                
   });
   alert(records.length);//This displays 0
   alert(records.length);//This alert correctly displays number of records

The problem is that the array records appears empty, if I try to use them immediately after calling ajax (first alert displays zero length, while second alert displays correct length). What's the problem and how to solve it?

gorill
  • 1,623
  • 3
  • 20
  • 29

2 Answers2

3

You just need to put your alert inside the success callback.

   var records = [];
   $.ajax(
   {
        url : "index", 
        dataType: 'json',
        success: function (response)
        {
           records = response;
           alert(records.length);  // will always be correct
        }                
   });

In your example, the behavior will be unpredictable and will depend on how fast the call returns.

Jonah
  • 15,806
  • 22
  • 87
  • 161
2

The A in Ajax stands for Asynchronous

The success function doesn't trigger until the HTTP response comes back.

When the first alert fires, it hasn't come back. In the time it takes for you to click OK to that alert, the response has arrived so the success function has run by the time the second alert fires. (alert is a blocking function).

Do your work on the data in the success function, not immediately after sending the HTTP request.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335