How call async funcion after ajax call
How call async funcion after ajax call
vahidsam
Posts: 6Questions: 2Answers: 0
I want to manipulate the data after receiving it from the server.
I tried to call async funtion in dataSrc section like following example but I cant show the data on the table.
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"dataSrc": async function ( json ) { // I added async
// call async funtion here
json.data = await myfunction(json)
return json.data;
}
}
} );
This question has accepted answers - jump to:
Answers
Not sure why you are trying to use an async function. Is
data.json
being served by a web server or the local file system?Maybe you want to use
ajax
as a function. Its hard to say without knowing more about what you are trying to do.Kevin
Hi Kevin,
that was my fault. Data comes from the web server. But the response data from server is encoded. To decode the data I need to call another asynchronous function (here myfunction() ) and then the data can be displayed in table.
I'm not sure if
ajax.dataSrc
supports an async function. @allan can confirm.One option is to use jQuery ajax() to fetch and process the data. Once complete you can initialize Datataables with the
data
option. Or initialize an empty Datatable then userows.add()
.Kevin
I am using the table with Severside processing and pagination. it means, if user clicks on another page, the new data should be recieved from server.
I think initializing an empty table is not really helpfull.
Sorry, didn't realize you were using server side processing. My above answer won't work for that case.
If the
ajax.dataSrc
callback doesn't support aync functions maybe you can usexhr
to process the data.@allan may have other suggestions for you.
Kevin
I tried using the xhr event as async function to process and manipulate the data like in the example below. But so far it doesn't work properly and I get an error message as alert and table is displayed empty.:
DataTables warning: Requested unknown parameter '0' from the data source for row '0'
That is just assigning the result of the
decodeData
Promise to the local variable. It isn't a "pointer" in the C sense whereby the calling function would then have access to it.Also our event handlers don't expect async functions - so they don't wait for the Promise to complete.
For this sort of behaviour you would need to use
ajax
as a function and make the Ajax call yourself along with the async post processing.Allan
Hmm, the
xhr
event might not support async functions. Do you need to use an async function?Possibly you can use
columns.render
to decode just the columns needed. You probably won't want an async function there either.Possibly create a rendering plugin.
Kevin
Possibly use
ajax
as a function. Here is a Scroller example then might give you some ideas.Kevin
I found the solution and it works for me.
many tnx to Kevin and Allan.
Very nice!
Kevin