Can not push to javascript global array varible


This question already has an answer here:


As Bojangles mentioned, this is because your code is executed asynchronously.

When the JS Interpreter reaches the $.getJSON line, the browser sends a request to get the desired data. As soon as the server responds, your callback function gets invoked. But in the meantime, the interpreter reaches drawKomp(0), before the server responded.

As the ajax call takes some time, it would be insane if the interpreter would stop execution here. Thats why you provide a callback function.

So code execution looks like this:

Send request to JSUrl and remeber function(data){...} to be executed when you got data
call drawKomp(0)
ajax call finished, call function(data){...}

So you have to make sure, that drawKomp(0) does not get called before your data is pushed to your array.

The easiest way to fix this would be:

$(document).ready(function () {
    $.getJSON(JSurl + "/Home/getServicesForCustomer?name=" + '@Model', function (data) {
        $.each(data, function (index, value) {
            console.log("Trying to push services : " + JSON.parse(value.jsonTEMPLATE).komponent);
            console.log("After push : " + services);



This way, your drawKomp gets executed after the json is loaded and processed.

You can also work with Deferred objects, but that could get complicated.

Need Your Help

result with "like" in query using doctrine 2

sql symfony doctrine-orm

In my news web page I would like to have a related news using "keywords" quoted in principal news and im using this query :

JSON repsonse encoding problems

iphone ios json

I have ASIHTTPRequest with JSON response. I use SBJsonParser for JSON parsing, I need parse some strings from response. But I have problem with Russian symbols, I receive russian strings like:–†–Њ—...