2

OK, here's the situation - simple and clear :

  • On Page A : We perform an ajax request (let's say to intermediate.php) which initiates a background process - let's say back.php
  • interm.php returns
  • back.php keeps working until it finishes, while updating its progress in a db.

So, how could Page A get notified that back.php has finished?

(I've thought e.g. of firing an ajax request every 1-2 secs to a script checking the db for back.php's progress, but that seems pretty weird and definitely not efficient...)

Any ideas?

Dr.Kameleon
  • 21,495
  • 19
  • 103
  • 208
  • The ajax call is asynchronous, so there's no real gain in running a PHP script as a background proccess. Could'nt you just run it the regular way, and keep the xmlHTTPrequest open until the PHP script finishes, and return something (default is 30 sec allowed in PHP to keep connection open) ?? – adeneo Aug 01 '12 at 02:23
  • @adeneo 1) My script may need to run for over 2-3 minutes. 2) The script is split in various sub-tasks (so I want to be notifying the user on the progress - e.g. 2 out of X complete). 3) Obviously, I have to know when the whole thing finished. :-) – Dr.Kameleon Aug 01 '12 at 08:44

2 Answers2

6

You could do a long-polling or short-polling technique which is quite common and not so weird. It does make a lot of unnecessary requests, but it's the simplest and most supported method out there.

The second method would be using web sockets. Now web sockets through html5 are not generally supported as of now, but an alternative would be to use a library that takes care of fallbacks to other methods such as flash, or even long-polling if your browser / device doesn't support a previous method. A really good library for real-time communication would be Socket.IO. It allows many different implementations of real-time or close to real-time, it also allows you to choose which method of communication you want to use. Some cloud based web services such as Paas don't widely support web sockets. Libraries will go around this by letting you choose or force a specific method of communication: Web Sockets, Flash Sockets, Long-Polling, etc..

But since your using php, you could try this: https://github.com/lemmingzshadow/php-websocket

Though as mentioned on some of these sites, using websockets with php is not as straight forward as node.js or twisted python. But nonetheless it's achievable and does work at some degree. I found that having a node.js backend to do the real-time stuff is a lot easier then trying to force a technology that is not meant to be worked in that way.

Community
  • 1
  • 1
Daniel
  • 1,610
  • 2
  • 13
  • 19
1

What you're basically looking for is Comet. Here's a good thread on it:

Using comet with PHP?

Community
  • 1
  • 1
Alex Weinstein
  • 9,499
  • 8
  • 38
  • 58