Cyval
Cyval

Reputation: 2519

Cannot read property 'length' of undefined AJAX

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 .

Upvotes: 0

Views: 393

Answers (2)

Shomz
Shomz

Reputation: 37701

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.

Upvotes: 3

gegillam
gegillam

Reputation: 136

You need to call addTableHeaders inside of ajax success

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

});

Upvotes: 0

Related Questions