0

I am using the Query POST AJAX to get data from database. Problem is the function does not returning any value. Here's my code.

var graph = {
        _ds2: [],
        display_graph: function(){
            graph._data = [];
            _data = "class=graph&func=get_all";
            $.post(window.location.href, {async: false}, _data, function(data){ 
                var data = $.parseJSON(data);
                //console.log(data)   
                for (var i = data.length - 1; i >= 0; i--) {
                    _ds1 = [];
                    _ds1.push(parseInt(data[i]['year']), parseInt(data[i]['income']));
                    graph._data.push(_ds1);
                };
               ///graph.create_graph(graph._ds2.reverse());
               //return graph._data;
            });
            return graph._data;
        }

}

I call the function like this.

$(document).ready(function(){  
        /* graph 1*/
        console.log(graph.display_graph()); 
    }); 
  • 1
    Note that the arguments for `$.post` is as follows, `$.post(url, data, callback, dataType)` – adeneo Apr 13 '14 at 11:25
  • @adeneo. Can you give me the possible solution of this problem. I already research about it but never get any solutions. I already tried setting the async to false, used callback. none of these solved my problem. Thanks – user3528843 Apr 13 '14 at 11:36

1 Answers1

0

You are returning a var without waiting to ajax to finish. Inmediately after the app reads the post executes the return but the ajax has not finished yet. I suggest you to use callback like this:

function foo(){

    fooAjax(function(data){ console.log(data) } //data is the data retrieved by the ajax
}

fooAjax(callback){

    $.ajax({
           success: function(response) {
               callback(response)
           });
}

The parameter passed to fooAjax is the callback function, its like a """"variable"""" function passed as reference.

Success is deprecated but it is still working (now we can use .done()). Other way is using deferred objects: they are like object passed locally to an Ajax, you can acceed at Ajax .done().

grivcon
  • 131
  • 9