Note that there are some explanatory texts on larger screens.

plurals
  1. POAJAX polling of a URL returning JSON doesn't seem to return fresh responses (using jQuery $.ajax() method)
    text
    copied!<p>My project requires polling a certain URL for a JSON response, using AJAX. The first AJAX request that I make alerts the server that I want some JSON content, and it begins building and cacheing a response, sending me back <em>{ "status" : "pending" }</em> for each subsequent AJAX request until the JSON is ready. At that point, the response changes to JSON that contains content that I can parse and display in the document, which I want to do as soon as the URL returns anything other than <em>{ "status" : "pending" }</em>.</p> <p>I've set up a polling function that works as expected to repeatedly request JSON from the URL. However, the problem is that it continues to get the response <em>{ "status" : "pending" }</em> even when I navigation directly to the URL and can see that the full JSON response is ready and is being served. For some reason, my polling function still gets <em>{ "status" : "pending" }</em>.</p> <p>When I refresh the page that contains the polling code, it generally works on the first request - i.e. it gets the full JSON response. That leads me to believe that it's some sort of caching issue, but I'm not sure where or why. Shouldn't each AJAX request get a fresh response, or is this something I can set up in my <em>$.ajax()</em> call?</p> <p>Here's the code I'm using now:</p> <pre><code>function ajax_poll() { $.ajax({ url: JSON_URL, // JSON_URL is a string containing the URL to poll dataType: 'json', error: function(xhr_data) { display_error(); }, success: function(xhr_data) { if (xhr_data.status == 'pending') { poll++; // increment poll counter // poll is a global variable to track the number of requests made if (poll &lt; POLLS) { // POLLS is a global variable to set the maximum number of requests setTimeout(function() { ajax_poll(); }, INTERVAL); // wait INTERVAL before another AJAX request } else { display_error(); } } else { success(xhr_data); } }, contentType: 'application/json' }); } </code></pre> <p><em>success()</em> is the function that displays the JSON content (i.e. what I'm waiting for to become available while polling) on the page.</p> <p>One thing worth noting is that while testing the code locally, polling a local .json test file, I can change the file's contents from <em>{ "status" : "pending" }</em> to a response containing content like I'm looking for, save the file between polling instances, and on the next poll, my code sees the new content and works as expected. It just isn't working in the staging environment.</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