0

I have searched throughout SO about this issue, but I'm not getting any results in my code.

I have a simple JSON parser here, which creates a table based on a JSON object returned by an endpoint. Here is what I have tried so far.

function getAJAXData(APIurl){
$.ajax({
    url: APIurl,
    type: "GET",
    dataType: "json"
}).then(function(data){
    alert(data);
});
}

function generateTable(tableId){

var objRecords = getAJAXData("http://jsonplaceholder.typicode.com/posts");
var cols = addTableHeaders(objRecords, tableId);

for(var i = 0; i < objRecords.length; i++){

    var tRow = $('<tr/>');

    for (var colIdx = 0; colIdx < cols.length ; colIdx++){

        var cellVal = objRecords[i][cols[colIdx]];

        cellVal = (cellVal == null) ? "" : cellVal; 

        tRow.append($('<td/>').html(cellVal)); 
    }
    $(tableId).append(tRow);
}
}

function addTableHeaders(myList, tableId){
var colSet = [];
var headers = $('<tr/>');

for (var i = 0; i < myList.length; i++) {
    var hRow = myList[i];
    for(var key in hRow){
        if($.inArray(key, colSet) == -1){
            colSet.push(key);
            headers.append( $('<th/>').html(key) );
        }
    }
}
$(tableId).append(headers);

return colSet;
}

That one doesn't work but when I hard-code a list, it generates a table from the hard-coded list. Can someone please explain what I am doing wrong or missing in the code? Thanks .

Cyval
  • 2,429
  • 4
  • 16
  • 27
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jaromanda X Jan 11 '16 at 01:07

2 Answers2

3

These two lines are an issue:

var objRecords = getAJAXData("http://jsonplaceholder.typicode.com/posts");
var cols = addTableHeaders(objRecords, tableId);

First off, your getAJAXData function doesn't return anything, so objRecords will always be undefined.

Second, even if it did return something, it's an asyncronous call, so the data won't be ready right away.

What you need to do is to wrap up the relevant bits of your code into a function and call it on the success callback so it gets executed only after your AJAX data is ready.

Shomz
  • 37,421
  • 4
  • 57
  • 85
0

You need to call addTableHeaders inside of ajax success

$.ajax({
    url: APIurl,
    type: "GET",
    dataType: "json",
    success: function(data){
    //call it  here
    }
})

});
gegillam
  • 126
  • 7
  • its because the way ajax works, your whole for loop runs before your ajax call returns data, so when you try to use that data it is undefined. – gegillam Jan 11 '16 at 00:45