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 { "status" : "pending" } 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 { "status" : "pending" }.
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 { "status" : "pending" } 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 { "status" : "pending" }.
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 $.ajax() call?
Here's the code I'm using now:
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 < 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'
});
}
success() is the function that displays the JSON content (i.e. what I'm waiting for to become available while polling) on the page.
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 { "status" : "pending" } 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.