Get array value from AJAX request

11,219

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

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();
Share:
11,219
bodruk
Author by

bodruk

Hello, world! I'm a brazilian project manager who loves programming, web, games, technology and useless gadgets.

Updated on June 05, 2022

Comments

  • bodruk
    bodruk almost 2 years

    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.

  • Heretic Monkey
    Heretic Monkey over 7 years
    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?