I need to execute a long (10-60 sec) PHP task from Ajax. Furthermore, the calling page needs to close the connection and go to a new page, with the PHP task finishing in the background.

At first I tried this scenario:

   url: '/ff.php',  
   type: 'POST'
}).success(function(response) { 
   console.log("... returned");
window.top.location.href = "http://yahoo.com";      

But that never executes ff.php as I thought it should. Somehow it goes to the new page before calling the Ajax... or the connection is closed due to the new page, before it executes. This, despite the precautions I thought I needed in ff.php:

header("Connection: close");
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
// Do processing here 




I've seen numerous posts that that top block of code is what's needed to have the PHP return control to the caller immediately but I can't get it to work in this scenario -- I suspect it's because I'm moving to a new page. That last require statement sends a push notification to my app on my iPhone, which woks just fine. I use this to know that my PHP script has been executed and it will part of my production environment when this works.

I have also tried moving the new page URL into the Ajax success block as follows, since I thought the PHP had all the code necessary to return immediately.

   url: '/ff.php',  
   type: 'POST'
}).success(function(response) { 
   console.log("... returned");
   window.top.location.href = "http://yahoo.com"; 

But in that case, it takes the full 30 secs before going to the next page.

The desired results are: execute the PHP, receive the push right away, and the page goes to the next page quickly. But so far I either get the next page immediately, with NO execution of ff.php or, it does execute but the browser waits the full 30 secs to go to the next page.

UPDATE: As one commenter said below "basically if you redirect before the response then your ajax call will be cancelled." ... so my follow up question is this... is there no way to know when the Ajax has been received and started execution, so I can do the redirect at that time? I looked through the Ajax events and they all seemed to be related exclusively to when execution is complete. Does this imply there is no way to handle a long ajax call via jQuery? We have to use a queue?

2016/08/13 21:01
  • php
  • ajax
  • jquery
  • 点赞
  • 收藏
  • 回答