title: Ajax call for long PHP task
body: <p>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.</p>
  
  <p>At first I tried this scenario:</p>
  
  <pre><code>$.ajax({
     url: '/ff.php',  
     type: 'POST'
  }).success(function(response) { 
     console.log("... returned");
  });
  window.top.location.href = "http://yahoo.com";      
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>ignore_user_abort(true);
  ob_end_clean();
  header("Connection: close");
  ignore_user_abort();  
  ob_start();
  echo ('Text the user will see');
  $size = ob_get_length();
  header("Content-Length: $size");
  ob_end_flush();  
  flush();             
  // Do processing here 
  
  session_write_close();
  
  sleep(30);
  
  require_once($_SERVER['DOCUMENT_ROOT'].'/ajax/lib/sendPush.php');
  </code></pre>
  
  <p>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.</p>
  
  <p>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. </p>
  
  <pre><code>$.ajax({
     url: '/ff.php',  
     type: 'POST'
  }).success(function(response) { 
     console.log("... returned");
     window.top.location.href = "http://yahoo.com"; 
  });
  </code></pre>
  
  <p>But in that case, it takes the full 30 secs before going to the next page.</p>
  
  <p><strong><em>The desired results are: execute the PHP, receive the push right away, and the page goes to the next page quickly.</em></strong> 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.</p>
  
  <p><strong>UPDATE</strong>: As one commenter said below <em>"basically if you redirect before the response then your ajax call will be cancelled."</em> ... 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?</p>