views:

345

answers:

2

Just like in SO, where one is answering a question, if somebody has answered said question, a notification will appear (via AJAX?). My only way of somewhat replicating this is by including a timeout on my script that fetches if there is an update every n seconds. Is there a way to do this using observer pattern on PHP + Javascript (w/ jQuery)?

A: 

If you use timeouts to query the server for updates, it may still be considered a peculiar implementation of the Observer pattern. Unfortunately, it's not possible to do it the other way around. If the server finishes responding to the main HTTP request, the client just finishes "listening" to it. The only way to do this is to make an asynchronous request from the client.

Ignas R
+1  A: 

you have to look at the ReverseAJAX or COMET methodologies.

As per wikipedia

Reverse Ajax refers to an Ajax design pattern that uses long-lived HTTP connections to enable low-latency communication between a web server and a browser. Basically it is a way of sending data from client to server and a mechanism for pushing server data back to the browser.

EDIT:

i suggest you to implement the following approach, this is simple to implement. I take stackoverflow answering as an example.

  1. After the answer page load complete. Initiate a AJAX request (Asynchronos, so it wont block the UI)
  2. And it will look for any new updates on the server side (polling the DB to check if any new answers added)
  3. And return the data only to browser, if there is an update. otherwise stay calm.
  4. After returning the data to client, client should invoke the another AJAX request and wait for the updates.
  5. Repeat step 2 to 4 for the rest of the page life time.

Hope this helps.

Cheers

Ramesh Vel

Ramesh Vel
Thanks for the links, the client and long polling topics got me thinking. Lots of ideas popping to my head right now. But I need more concrete answers. Thanks anyway.
mives
@mives, i just updated my ansewer, check out..
Ramesh Vel