2

I have a PHP process that takes a long time to run. I don't want the AJAX process that calls it to wait for it to finish. When the PHP process finishes it will set a field in a database. There should be some kind of AJAX polling call to check on the database field periodically and set a message.

How do I set up a jQuery AJAX call to poll rather than wait? Does the PHP script have to do anything special?

dnagirl
  • 20,196
  • 13
  • 80
  • 123

4 Answers4

2

It's easier to have your server-side action, simply respond with a negative response until the value is ready and set up the client-side to repeatedly poll (with setTimeout()) until a positive response is received or a fixed number of failures is observed.

 var timer;
 var count = 0;
 function poll(url) {
      timer = setTimeout(function() {
          $.ajax({
              url: url,
              success: function(data) {
                  if (data.Status) {
                      ...do something...
                  }
                  else {
                     if (++count > 10) {
                       ...failure action...
                     }
                     else {
                         poll(url);
                     }
                  }
              ...other options...
           })
      },5000)
 }

Then on the server side use something that does (pseudocode) ...

 if operation is not complete
     return serialize( { Status : false } )
 else
     data = ....
     data.Status = true
     return serialize(data)
 end
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
2

Step 1: The first call to the long running process - Set ignore_user_abort(true); in the PHP script which takes a long time and close the connection.

Step 2: Check if the DB field is updated using the methods suggested.

stackoverflow
  • 455
  • 3
  • 12
  • @stackoverflow: in Step 1, how do I close the connection? I'd thought to send a 202 (accepted) header, but usually that finishes with `exit()` which would terminate the script. – dnagirl Mar 22 '10 at 19:51
  • http://www.php.net/manual/en/features.connection-handling.php#71172 might be of help. – stackoverflow Mar 22 '10 at 20:48
0

One quick workaround would be to create another PHP script which you can call that will check for that, since accessing DBs directly thru AJAX's comm method is not a good practice.

  1. Create a PHP file, with the DB check required.
  2. Make it so it will post 'T' or 'F' or something like that
  3. Create a SetInterval('yourfunctionname',100) so you can call the polling script.
  4. If the answer fo that polling is 'T', call your other long-time script.
jpabluz
  • 1,200
  • 6
  • 16
0

Do you mean usual polling (as opposed to long polling)? If yes, maybe this helps: http://jquery-howto.blogspot.com/2009/04/ajax-update-content-every-x-seconds.html

The PHP script would just check the database field, and return true/false immediately.

Chris Lercher
  • 37,264
  • 20
  • 99
  • 131