Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery AJAX polling for JSON response, handling based on AJAX result or JSON content
    text
    copied!<p>I'm a novice-to-intermediate JavaScript/jQuery programmer, so concrete/executable examples would be very much appreciated.</p> <p>My project requires using AJAX to poll a URL that returns JSON containing either content to be added to the DOM, or a message <em>{ "status" : "pending" }</em> that indicates that the backend is still working on generating a JSON response with the content. The idea is that the first request to the URL triggers the backend to start building a JSON response (which is then cached), and subsequent calls check to see if this JSON is ready (in which case it's provided).</p> <p>In my script, I need to poll this URL at 15-second intervals up to 1:30 mins., and do the following:</p> <ul> <li>If the AJAX request results in an error, terminate the script.</li> <li>If the AJAX request results in success, and the JSON content contains <em>{ "status" : "pending" }</em>, continue polling.</li> <li>If the AJAX request results in success, and the JSON content contains usable content (i.e. any valid response other than <em>{ "status" : "pending" }</em>), then display that content, stop polling and terminate the script.</li> </ul> <p>I've tried a few approaches with limited success, but I get the sense that they're all messier than they need to be. Here's a skeletal function I've used with success to make a single AJAX request at a time, which does its job if I get usable content from the JSON response:</p> <pre><code>// 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' }); } </code></pre> <p>However, this function currently does nothing unless it receives a valid JSON response containing usable content.</p> <p>I'm not sure what to do on the lines that are just comments. I suspect that another function should handle the polling, and call ajax<code>_</code>request() as needed, but I don't know the most elegant way for ajax<code>_</code>request() to communicate its results back to the polling function so that it can respond appropriately.</p> <p>Any help is very much appreciated! Please let me know if I can provide any more information. Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload