1

I have created a small JavaScript application with the following function that calls a function to retrieve JSON data:

var months = function getMonths(){

$.getJSON("app/data/Cars/12Months", function (some_data) {
    if (some_data == null) {
        return false;
    }

    var months_data = new Array();
    var value_data = new Array();

    $.each(some_data, function(index, value) {
        months_data.push(index);
        value_data.push(value);
   });

    return[months_data,value_data];
});

}

I have then created, in the same file, another function that does something when a specific page is loaded. In this function the variable 'months' is passed to the variable 'result'.

$(document).on('pageshow', '#chartCar', function(){

$(document).ready(function() {


    var result = months;
    var date = result[0];
    var values = result[1];

//more code here...

});
}

the problem is that, based on the debugger, the getMonths() function works fine and produces the expected output, but the 'result' variable in the second function can't obtain the values passed to it by the variable 'months'. Do you know how to solve this issue?

1
  • Can you please explain? Commented Mar 6, 2013 at 10:06

3 Answers 3

2

The problem is that you $.getJSON() function is asynchronous, so your data gets loaded later then you read it. There're two workarounds:
1. Replace your $.getJSON with $.ajax and setting async: false;
2. Put your code in $.getJSON callback:

var months = function getMonths(){

$.getJSON("app/data/Cars/12Months", function (some_data) {
    if (some_data == null) {
        return false;
    }

var months_data = new Array();
var value_data = new Array();

$.each(some_data, function(index, value) {
    months_data.push(index);
    value_data.push(value);


}); 

var date = months_data;
var values = value_data;
//more code here..
    })
    }
Sign up to request clarification or add additional context in comments.

Comments

0

There must be a syntax error.

replace

});
}

With

});
});

Comments

0

$.getJSON() is a wrapper around $.ajax which is async by default. But you treat it like a sync call.

You can use $.ajaxSetup()

$.ajaxSetup( { "async": false } );
$.getJSON(...)
$.ajaxSetup( { "async": true } );

or use $.ajax with async: false

$.ajax({
    type: 'GET',
    url: 'app/data/Cars/12Months',
    dataType: 'json',
    async: false,
    success: function(some_data) { 
        //your code goes here
    }
});

or if possible change the behavior of your app so that you process your data in a callback function.

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.