treehouse : what would you like to learn today?
Web Design Web Development iOS Development

How to 'push' data onto a webpage

  • Hiya!

    Just wondering how I'd go about updating a webpage without refreshing it - a bit like twitter does. I was originally thinking about a set time out function running an ajax request, but then I thought perhaps there's a way to only update as something changes (not every few seconds) a bit like facebook's web chat.

    Can anyone point me in the right direction?

    Thanks! Dave
  • Browsers don't support "push". A server cannot initiate a request and push data to the browser.

    A technique that Gmail's chat uses (and I'm assuming Facebook's as well) is the "hanging request" technique. Here's how it works. The browser sends a request to the server. The server refuses to respond to that request until it has something to give it. After a long period (like a couple of minutes maybe) the request will eventually timeout since that's the nature of HTTP. The client code is ready for this and just opens another request; the client is responsible for making sure that a request is always open; that way, when the server sees that any data is ready, it can immediately respond.

    Open any tool that shows HTTP requests (Firebug, Chrome's developer tools, Fiddler, Charles, etc) and use one of these chats to see what I'm talking about.

    In my opinion, this is even easier than the "polling" approach used on a timeout. It uses less bandwidth too. Hope that helps :)
  • Hey akeenlabs, thanks so much - great response. I'm going to look into all the stuff you just said, all I need now is an excuse to use it...

    Thanks again, Dave : )