1

I'm trying to feed an array several times using multiple jQuery's get JSON functions. And use the array after all the data is inserted.

The problem is that the data only scopes inside each function and I can't feed the array with multiple separate functions, for example:

var array;
array = [];

//Now I use getJSON to call a php with a json output and push the response

$.getJSON('../includes/comOne.php', function(response){

   //Here I get a JSON formated object that I push into the array

    array.push(response);

Everything is fine and if I log the array I get the object entities created in the JSON objects and each value.

    console.log(array)

Output:

[Array[2]]0: Array[2]0: ObjectdateUpdate: "2015-04-04 19:39:16" intID: "1" strDate: "56" strFfb: "tete"strFig: "tete"strFront: "testrfront"strFtw: "tete"strHeader: "testhe"strText: "testtext"strType: "Native"strVideo: "tete"proto: Object1: ObjectdateUpdate: "2015-04-04 19:39:16"intID: "2"strDate: "12"strFfb: "fsf"strFig: "sfsfs"strFront: "fsfsfsfsfsf"strFtw: "sfsfsfs"strHeader: "tetetetetetetetetetetete"strText: "fsfsfsfsfsfsf"strType: "Native"strVideo: "fs"proto: Objectlength: 2__proto__: Array[0]length: 1__proto__: Array[0]

})

But if I try to log the array outside the getJSON function the array is empty

console.log(array);

Output:

[]

I've tried to create the json function inside a variable and return the response, but I loose the array.

Thanks!

1 Answer 1

1

That is because your ajax function is asynchronous: You fire your ajax request and then you move on to show the array. That will still be empty because the $.getJSON() function has not finished yet.

You should check that all your ajax requests are finished and only then use the array. You can use something like $.when() for that.

For example:

var array = [],
    call1 = $.getJSON(...),
    call2 = $.getJSON(...);

$.when(call1, call2).then(...);
Sign up to request clarification or add additional context in comments.

Comments

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.