How are these two same data sources different? One works one doesn't.
How are these two same data sources different? One works one doesn't.
DanJ210
Posts: 23Questions: 5Answers: 0
The code below shows a variable being set to the same JSON data that the metalTable dataSrc is getting. I've alerted both of them. Both do the exact same thing and parse into data. The code below loads data into the datatable but if I get rid of the ajax call and only use the data1 variable, which is parsed the same, the datatable says no data in table. There's no error or nothing. So I can't figure out how that's any different than the ajax call within the datatable.
var data1 = $.get('Price/ReturnTableJson', function (data) {
var parsedObject = JSON.parse(data);
//alert(data);
return parsedObject;
});
//alert(JSON.stringify(data1));
var metalTable = $('#metalTable').DataTable({
ajax: {
url: 'Price/ReturnTableJson',
dataSrc: function (data) { alert(data); var parsedObject = JSON.parse(data); return parsedObject; },
},
columns: [
{ data: "CommodityName" },
{ data: "CommodityPrice" }
],
});
This discussion has been closed.
Answers
Hi @DanJ210 ,
When you say, "if I get rid of the ajax call and only use the data1 variable", how are you using it? As the
ajax.url
, or asdata
? It should be the latter, since the data just needs to be slotted into the table.If you have no joy, It would be worth posting the results of both the
alert
calls, and show how you initialise the table in both instances,Cheers,
Colin
I use the data attribute when I remove the ajax call. Here's the alert for both code calls. They both alert the same thing. They are both a get ajax call and I alert the data before parsing into an object. In the second example code block I am using the variable data1 as the data source for the datatable and it should work because it's the same exact data object as in the first example ajax call.
And I believe you are seeing how I'm initializing the table.
Hi @danielj210 ,
The problem is the async nature of the Ajax call.
If you look at this example here, the first two tables are similar to what you're doing. So, in the second one, by the time the data has return, the table would've already been initialised without that data, hence it's empty.
The fix for your second one, is the third one in that example above - here, it waits for the data to be returned before initialising the table,
Cheers,
Colin