Long polling ajax requests with DataTables
Long polling ajax requests with DataTables
Hello folks,
I can't quite get around this idea and if someone could propose a solution it will be great.
Currently I have an restful API, which works great with DataTables.
The problem I currently have, I want to expose into the API some operations, which might be time consuming. So instead of making an AJAX request and waiting for the request to complete, I was thinking something like:
- Send an Ajax request and return "job handle" (for example: jobX)
- Process the jobX into the background, using Gearman or something different.
- DataTables should ask for the job status each second for example, and once the job has completed just to draw the table.
So ideal would be into my initialisation:
"sAjaxSource": "/api/long_taking_oepration",
and somehow to make DataTables automatically check "/api/job_status?job=jobX"?
Any thoughts and advices?
Thanks!
Answers
Your stumbling point will be point 3. DataTables knows nothing about your external API, and shouldn't (it would be different for every implementation!). What I would suggest is that you provide the code that checks the job queue to see if jobs are done and if so then have it use the DataTables API to add the rows (
rows.add()
.).Regards,
Allan
I was thinking more likely hooking into some of the callbacks in order to query the API and check the job if it's finished.
My first try of the implementation is:
however I am not sure if that's the correct place to hook and implement something like that. Any thoughts?
I would suggest probably not there. Are you planning on using server-side processing or client-side? That is certainly going to be the key question. For client-side, you probably would get away with that. For server-side, no (I'm not sure how this would be done with server-side processing atm to be honest).
I think just running your poll and then using the API to add rows would probably be the best way. But I'm sure there are many ways to do it!
Allan
I use Datatables in combination with SignalR to do just this thing. The table loads and then SignalR pushes the update when complete. If you can use a framework such as SignalR then its trivial to just create a handler that inserts rows. (this is my preferred method).
In another implementation I also use a standard javascript timeout to just poll the server. As soon as the table loads a timer kicks off and just looks for updates from the server ever 10 seconds or so.
This is roughly how i achieved this using standard a timeout poll.
Hope this may prove useful.
Nice one - thanks for sharing your code with us!
Allan