2

I have a script that reads a JSON file then populates an array with the name property of each element.

HTML

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var a = [];

var myMethod = function(){
    $.ajax({
        url : "numbers.json",
        dataType : "json",
        success : function(data){
            for(i in data){
                a.push(data[i].name);
            }
        }
    });
}

myMethod();
console.log(a[2]); // console.log() returns "undefined"
</script>

JSON

[
    {"name" : "One"},
    {"name" : "Two"},
    {"name" : "Three"},
    {"name" : "Four"},
    {"name" : "Five"}
]

I cant't access a specific index of this array. The console log always returns undefined. I've tried to add .then() after my ajax call, but it doesn't work too.

bodruk
  • 3,242
  • 8
  • 34
  • 52

4 Answers4

4

You'll wanna do something like this:

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var a = [];

var myMethod = function() {
    $.ajax({
        url: "numbers.json",
        dataType: "json",
        success: function(data) {
            for (i in data) {
                a.push(data[i].name);
            }
            handleData();
        }
    });
}

function handleData() {
    console.log(a[2]);
}

myMethod();
</script>

Javascript won't wait for all of your code to run line by line, so for asynchronous calls you'll need a seperate function to handle data OR to handle the data within the success callback. Another function would be cleaner though depending on what you want to do with the data.

Jeremy Jackson
  • 2,247
  • 15
  • 24
3

Your console.log(a[2]); runs before AJAX finishing processing, because of AJAX's asynchronous nature, that's why it returns undefined. Put the console.log inside AJAX success. See the working snippet:

var a = [];

var myMethod = function(){
    $.ajax({
        url : "https://api.myjson.com/bins/b4bnr",
        dataType : "json",
        success : function(data){
            for(i in data){
                a.push(data[i].name);   
            }
           console.log(a[2]);
        }
    });
}

myMethod();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can read more about how AJAX works here.

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
2

Your're running an asynchronous request using $.ajax function so you should wait for the response then call the console.log inside success callback when the response is received from the server-side else the console.log will not work since the query is pending :

success : function(data){
     for(i in data){
         a.push(data[i].name);
     }
     console.log(a[2]);
}

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • This question has been asked multiple times over the years, and we have a canonical duplicate for it. Any reason you're not using your gold badge to mark this as a duplicate? – Heretic Monkey Jan 10 '17 at 14:59
2

The myMethod function completes when the ajax call completes and it moves on to the next line which is the console.log. The success only executes after the request to numbers.json returns. Try this:

var a = [];

var myMethod = function(){
    $.ajax({
        url : "numbers.json",
        dataType : "json",
        success : function(data){
            for(i in data){
                a.push(data[i].name);
            }
            console.log(a[2]);
        }
    });
}

myMethod();
MikeS
  • 1,734
  • 1
  • 9
  • 13