简体   繁体   中英

jQuery ajax call never finishes (success and error callbacks are not fired)

I've an ajax request to the server and I only need to know when it finishes to redirect the user to a second page. It is working most of the times but if the server takes too long to answer (eg 10 min) then it can happen that no callback function is called and the request keeps waiting.

My code is as follows:

$.ajax({
      type: 'post',
      url: 'request.php',
      success: function(data) {
            alert("Success: "+data);
            window.location.replace("success.php");
      },
      error: function (xhr, ajaxOptions, thrownError) {
            alert("Ajax error: "+xhr.status+" - "+thrownError);
            window.location.replace("error.php");
      }
});

As you can see, I've tried to check if there is any error but as far as I have arrived, the ajax request behaves as if it had not finished (no alert or redirection is fired). However, the PHP code in the server runs without errors until the end.

I have no idea where to search for the error because I was thinking about a timeout problem both in the browser or in the server but it seems not to be the cause. And as the same code is working in short waiting times I cannot imagine other possible reasons.

Thank you!

I would bet on a timeout on your web server which invalidates the connection, this might mean that no answer is sent back. In that case, the ajax timeout option might be good for you.

Having said that, if I were you, I would do this differently: since you're already using ajax, why not ping the server every x seconds and check if the process has finished and it's time to redirect, instead of keeping the connection open? This way you don't have timeout issues, and you don't hold the connection captive over a session which doesn't send any data and only waits for a server side process to finish. More scalable and robust, and more appropriate for http connections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM