How to merge data from many Ajax requests
How to merge data from many Ajax requests
Meeth
Posts: 3Questions: 1Answers: 0
I would like to know how to combine the json data from multiple API calls into one object. Essentially, this is what I would like to do:
$('.table').DataTable({
ajax: {
url: 'url-1.com' + 'url-2.com',
dataSrc: ''
},
columns:[
{ 'data' : 'firstName-from-url-1' },
{ 'data' : 'surname-from-url-1' },
{ 'data' : 'balance-from-url-2' },
{ 'data' : 'comment-from-url-2' }
],
});
This question has accepted answers - jump to:
Answers
This won't work as you can only define one URL. You could use the
ajax
option as a function and inside the function use jQuery ajax to fetch the multiple API's. Then use a loop to combine the responses into one object to return to Datatables. This example usesajax
as a function.Or you can use the same technique with jQuery ajax outside of Datatables. You can either initialize an empty Datatable, ie no
ajax
option, before calling the API's or you can init Datatables after all the data as been combined with thedata
option.The tricky part, since ajax is asynchronous, is using tow ajax requests to fetch the data and combining it. This CO thread has a couple opions.
Kevin
I think I will use a loop to combine the results. I'm trying to figure out how the
callback
function works from anonymous function:I get the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
. I think I can fix this by passingdataSrc:''
into thecallback
function. But how can I set thedataSrc
property from thecallback
function?Without seeing what you have its hard to say. One of the typical issues with this error is the number of columns in the HTML
thead
don't match the number defined incolumns
. Do you have twoth
defined in thethead
?I would do something like the example I linked to and place the data in the
data
object`, maybe like this:Kevin
Excellent! That worked. I think I will be able to take it from here. Thank you.