1

For some reason this does not loop through each object in my Ajax response into the array properly, I'm banging my head against a wall with this now.

My Ajax response is as follows...

{type:'blog_post',date:2013-30-12,title:'Blog Post',width:450,content:'qweqwe'},{type:'blog_post',date:2013-30-12,title:'Blog Post',width:450,content:'qweqwe'}

and here is the code...

var getTimelineData = function() {
    var tldata = [];
    $.get('/data/timeline_data', function(data) {
        $.each(data, function(i, val) {
            tldata.push(val)
            console.log(val);
        });
    });
    return tldata;
};  

The console log returns the exact response not as an individual array item.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
chris
  • 605
  • 1
  • 9
  • 27

3 Answers3

2

AJAX is asynchronous! When you call $.get, the AJAX call runs in the background and your code continues on. Later on in the future, when the AJAX call done, your callback function is ran. So, the return tldata; is run way before the AJAX call is finished.

You cannot return a value from an AJAX call, that's not how it works. I suggest passing a callback to the getTimelineData function. You can call it when the AJAX call is done:

var getTimelineData = function(callback) {
    $.get('/data/timeline_data', function(data) {
        var tldata = [];

        $.each(data, function(i, val) {
            tldata.push(val)
            console.log(val);
        });

        if($.isFunction(callback)){
            callback(tldata);
        }
    });
};

Then you can call it like this:

getTimelineData(function(data){
    console.log(data);
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

Perhaps one of the JSON cheker available online could help you. I often use http://jsonlint.com/

In JSON an array is declared with [], so I suspect the ajax answer should be more :

[
    {
        "type": "blog_post",
        "date": "2013-30-12",
        "title": "BlogPost",
        "width": 450,
        "content": "qweqwe"
    },
    {
        "type": "blog_post",
        "date": "2013-30-12",
        "title": "BlogPost",
        "width": 450,
        "content": "qweqwe"
    }
]
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
mpromonet
  • 11,326
  • 43
  • 62
  • 91
1

Your ajax response is invalid JSON. You should be wrapping it in [], if you want to return an array:

[{type:'blog_post',date:2013-30-12,title:'Blog Post',width:450,content:'qweqwe'},{type:'blog_post',date:2013-30-12,title:'Blog Post',width:450,content:'qweqwe'}]
ryanbrill
  • 1,981
  • 10
  • 13