Anto
Anto

Reputation: 4305

Passing data from variables in JavaScript

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?

Upvotes: 1

Views: 60

Answers (3)

peterm
peterm

Reputation: 92785

$.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.

Upvotes: 0

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

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..
    })
    }

Upvotes: 2

Devang Rathod
Devang Rathod

Reputation: 6736

There must be a syntax error.

replace

});
}

With

});
});

Upvotes: 0

Related Questions