1

I'm trying to get json data with $.getJSON and it's working fine. This is my code:

$(document).ready(function(){
    var MainArray = new Array();
    $.getJSON('check-location.php?onload=true', function(result) {
        $.each(result, function(i){
            MainArray[i] = result[i].CountryName;
        });
    });

    $(".drop-down").append("<div>" + MainArray[0] + "</div>");
});

I'm trying to assign it to array for later usage, but when I try to access it and display it I get undefined.

I get all the data for sure, but when I assign it to MainArray I cant access it outside the $.each function and I've no idea why.

1
  • Just a note. Go for [] instead of new Array(). Commented May 22, 2013 at 20:21

3 Answers 3

6

That's because Ajax is asynchronous, you are trying to append a non-existent value:

$.getJSON('check-location.php?onload=true', function(result) {
    $.each(result, function(i){
        MainArray[i] = result[i].CountryName;
    });
    $(".drop-down").append("<div>" + MainArray[0] + "</div>");
});
Sign up to request clarification or add additional context in comments.

Comments

3

Because $.getJSON is asynchronous, the MainArray isn't updated until the data is successfully returned.

But, the line

$(".drop-down").append("<div>" + MainArray[0] + "</div>");

will have already executed before the $.getJSON is completed...hence it is undefined.

You should move this somewhere and execute it when your data has returned, ie. in the callback

Comments

0

Like every body said, because its an asynchronous request you can turn that off (not a very good practice, but it will fix the problem)

Add this before the $.getJSON call

$.ajax({ async: "false" }); 

1 Comment

Thank you all for the help guys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.