I am a beginner JavaScript / jQuery programmer, so specific / executable examples will be much appreciated.
My project requires using AJAX to poll a URL that returns JSON containing either the content added to the DOM or the message {"status": "pending"}, which indicates that the backend is still working on generating a JSON response with content. The idea is that the first URL request starts the backend to create a JSON response (which is then cached), and subsequent calls check to see if this JSON is ready (in which case it is provided).
In my script, I need to poll this url at 15 second intervals until 1:30 minutes and do the following:
- If the AJAX request fails, exit the script.
- If the AJAX request succeeds and the JSON content contains {"status": "pending"}, continue polling.
- If the AJAX request succeeds and the JSON content contains useful content (that is, any valid response other than {"status": "pending"}), then display that content, stop polling and end the script.
I have tried several approaches with limited success, but I understand that they are all dirtier than they need. Here's the skeletal function that I used successfully to make one AJAX request at a time, which makes it work if I get useful content from a JSON response:
// make the AJAX request function ajax_request() { $.ajax({ url: JSON_URL, // JSON_URL is a global variable dataType: 'json', error: function(xhr_data) { // terminate the script }, success: function(xhr_data) { if (xhr_data.status == 'pending') { // continue polling } else { success(xhr_data); } }, contentType: 'application/json' }); }
However, this function currently does nothing until it receives a valid JSON response containing useful content.
I'm not sure what to do in lines that are just comments. I suspect that another function should handle the poll and call ajax _ request () as necessary, but I donβt know the most elegant way for ajax _ request () to pass its results back to the polling function, so that it can respond accordingly.
Any help is much appreciated! Please let me know if I can provide more information. Thank!
json javascript jquery ajax polling
Bungle Sep 10 '09 at 17:18 2009-09-10 17:18
source share