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

$.ajax({
    type:"GET",
    url:"question.xml",
    dataType: "xml",
    success: function(data) {

        $(data).find('item').each(function() {

            var question = $(this).find('question').text();
            var answer = $(this).find('qid').text();
            var opt1 = $(this).find('ans1').text();
            var opt2 = $(this).find('ans2').text();
            var opt3 = $(this).find('ans3').text();
            var opt4 = $(this).find('ans4').text();

            questions.push({'question':question, 'answer':answer, 'opt1':opt1, 'opt2':opt2, 'opt3':opt3, 'opt4':opt4});
        });
        alert(questions.length); // here it shows length as 20
    }
});
alert(questions.length); // here it shows length as 0 });

I have an array declared as global (questions), the problem is when I access the array inside the ajax success it has 20 elements, but when I try to access out the array length becomes 0.

Can someone explain what I'm doing wrong.

Lawson
  • 43
  • 1
  • 4

3 Answers3

1

$.ajax is async.

Your alert at the last line was executed before any questions are pushed in.

0

$.ajax queues a request to the web server and returns immediately.

Therefore, the bottom alert runs before the data is ready.

When the data is ready, the success function is run, and the data appears.

You should do any processing of the data in the success function, or by calling from the success function.

See How do I return the response from an asynchronous call? for confirmation and additional discussion.

Community
  • 1
  • 1
Paul
  • 26,170
  • 12
  • 85
  • 119
0

Ajax is asynchronous. This means that you order the browser to execute the ajax request, and the script will immediatelly continue with the rest of the script. Once the ajax request is completed, it will call the success handler of your ajax call. It will first reach

alert(questions.length); // here it shows length as 0

And when the page in your ajax call is finally loaded it will execute

alert(questions.length); // here it shows length as 20

If you need to perform actions on the result from the ajax call, you need to do it all in the success handler.

Sumurai8
  • 20,333
  • 11
  • 66
  • 100