views:

152

answers:

4

I have a situation where a display on a webpage needs to be updated at random. I am wanting to do this in AJAX but am not sure how to do this other than to do a

while(true) { ajaxFunction(); sleep(1) }

Type thing.

The problem with this is that the webpage needs to be updated very quickly on a change to the server, but the changes could happen very sporadically sometimes never.

EDIT: This is an Iphone application using a UIWebView, is it possible to use the iPhone's push notification to interface with the javascript?

Thanks!

A: 

If the changes are sporadic, consider not using any AJAX. Wait for the user to refresh or revisit the page.

mcandre
Like I said the user NEEDS to be be updated on the change to the display instantly
DevDevDev
"but the changes could happen very sporadically sometimes never"
mcandre
Still the client needs to know ASAP "webpage needs to be updated very quickly on a change to the server"
DevDevDev
"Is it possible to use the iPhone's push notification to interface with the javascript?"Tutorial: http://blog.boxedice.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/
mcandre
+4  A: 

I think what you're describing is Comet and there are a couple of plugins for jQuery:

http://code.google.com/p/jquerycomet/

http://plugins.jquery.com/project/Comet

Andy Gaskell
Cool thanks! The Long-polling sounds like it will work just fine for my uses.
DevDevDev
+1  A: 

The only way I can think of is to constantly query it. Just keep your responses small so you're not moving a bunch of data around for no reason. You could even suspend the response from the server until data is available.

setInterval(function(){
  $.get("updates.php", function(result) {
    alert(result);
  });
}, 5000);

Might even build some logic into updates.php to cancel the setInterval() after 10 minutes of inactivity on the users part. That will kill off constant requests from users who are no longer logged in.

Jonathan Sampson
+1  A: 

You should consider implementing some kind of a comet (server push) technology, when you want to optimize the servers load. If you only have a few users, than a polling solution is suitable.

About comet: comet technologies are nothing else, but making a simple http request to the server, where the server does not respond to the request immediately, but waits until there is something to respond with. Until than the thread on the server is suspended.

There are some technical aspects you should consider when implementing a server push technology (like where should I suspend the thread). It is best to use an open source one. It is easy to find them on the web if you search for comet.

Szobi
This is the solution I would have given, but I wouldn't have thought to use an external library to more fully complete the solution.
Stefan Kendall