Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Alexander Nortung
Alexander Nortung
6,930 Points

Server sent events

Hello recently i have been building an application for My website that uses Ajax to run a script that will update a part of the page, the problem is i believe Ajax polling takes a lot for the server and network to use when i am updating it every 2 seconds, imagine if there was 1000 people requesting the same thing every 2 seconds, that's not what i want.

My question is: how can i make it run the script for example whenever the database is updated or a new row was added? I would like to make something similar to a chat. I have read about server sent events, long polling and websockets, but I don't know what to use or how to use it with the current courses in the Treehouse library.

2 Answers

David Bath
David Bath
25,940 Points

You might enjoy this (non-Treehouse) tutorial: http://socket.io/get-started/chat/

There are several ways to get updates pushed from the server instead of frequently polling from the client. Long polling is where you send a request just as you do now, but instead of getting a response and requesting again in 2 seconds, the server waits to respond until there is new data to send. You can read more about it here: https://www.pubnub.com/blog/2014-12-01-http-long-polling/.

For a more real time connection there are technologies like WebSockets (https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) and server-sent events (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). I haven't used either of them, but I know codepen.io uses faye-websockets (https://www.npmjs.com/package/faye-websocket) for their Collab Mode and they have more than half a million users.

For a more exhaustive overview of all the options, check out the Wikipedia page on push technologies (https://en.wikipedia.org/wiki/Push_technology).

Hope this helps.