radhika radhika - 6 months ago 320
Javascript Question

JQuery .ajax timeout increase not working

I have a webpage where the javascript calls the PHP server using a POST request through the .ajax() function. The PHP server in turn calls an external third party API to submit a text analysis job. Once the text analysis job is processed, my PHP server queries the results from the API. However, the third party REST API does not provide any way to query the status of the job. So after I submit a job I put my program to sleep for about a minute and then query the results. However, sometimes my results are incomplete. I tried setting the sleeping time to be large but setting it to be longer than a minute seems to make the initial POST request from the Javascript to the PHP time out. Setting the ajax timeout parameter to be high doesn't help. Does anyone have suggestions on how this can be worked out? Any help is really appreciated.

The ajax request looks like this:

function callServer(params, success) {
var url = "ie.php";
$.ajax({
type: 'POST',
url: url,
data: params,
timeout: 60000000, //time out parameter doesn't work
dataType: "json",
success: function(result, textStatus) {
console.log(JSON.stringify(result, null, ' '));
if (success) success(result);
},
error: function(xhr, textStatus, errorThrown) {
var text = 'Ajax Request Error: ' + 'XMLHTTPRequestObject status: ('+xhr.status + ', ' + xhr.statusText+'), ' +
'text status: ('+textStatus+'), error thrown: ('+errorThrown+')';
console.log('The AJAX request failed with the error: ' + text);
console.log(xhr.responseText);
console.log(xhr.getAllResponseHeaders());
}
});
}


The error looks like this:

The AJAX request failed with the error: Ajax Request Error: XMLHTTPRequestObject status: (0, error), text status: (error), error thrown: ()

Answer

There are multiple places in the whole process with timeout settings:

  1. Browser / Ajax call
  2. PHP has its own: ini_set('max_execution_time', '1800'); or set_time_limit(1800);
  3. Apache itself has a max run time: Timeout apache2.conf
  4. Possibly your REST API - however you are calling it

The best case scenario in my opinion is to change from a blocking / synchronous strategy to an asynchronous strategy:

  1. Use ajax to send request from client to your server
  2. Run REST API from your server asynchronously (look up asynchronous curl or node.js)
  3. Client uses ajax to periodically query your server for status (maybe every 10 secs)

This makes the whole process asynchronous and doesn't require you to wait or block while the processing takes place

Comments