Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push new HTML data from the server to the browser without refreshing the page

I have seen many websites (facebook or stack overflow for instance) that will update certain features as new data is generated (new answer on a post for example).

Lets say that there is a new post added to a blog and someone is in the blog in that moment looking at it, the idea is to automatically add the new post to the blog without refreshing or having the user to do any action.

I have thought of executing an AJAX call every 5 seconds or so, but that will make too many requests to the server, and I saw that the websites I mentioned (which renew content) don't make any new requests.

I am really out of ideas of how to achieve this. Is this possible with PHP and AJAX? I've heard of websockets too. Any ideas? Thanks

like image 232
multimediaxp Avatar asked Apr 16 '13 04:04

multimediaxp


People also ask

How do you update HTML without reloading?

AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

How do I reload a DIV without reloading the whole page?

Use this. $('#mydiv'). load(document. URL + ' #mydiv');

How do I automatically refresh part of an HTML page?

Refreshing part of a page periodically You can use the frame “reload” function periodically in frameset page itself. In the above code, “right_frame” reloads every second. setInterval() function is very closely related to setTimeout() – both have similar syntax: setInterval ( expression, interval );


2 Answers

Great question! There's a few solutions.

There's been a relatively new solution to this call websockets. It's in the HTML5 standard and there's a lot of libraries for it on other languages too.

One of them is sockets.io ( javascript ) - it enables you to keep a consistent, low-latency connection with a server to receive information as it's generated. There's also plenty of plugins for php, c, and python for the server side.

To name a few: libwebsockets ( c++ ), pywebsockets ( python ), and jetty ( javascript )

And for php: http://socketo.me/

Visit this link for more info: http://www.html5rocks.com/en/tutorials/websockets/basics/

like image 162
tay10r Avatar answered Nov 15 '22 05:11

tay10r


You can use HTML5 SSE. But that's not a very good solution.

You can use Comet server that helps in Long AJAX polling. Check out the Ajax Push Engine (APE). It's a combination of Comet Server and a Javascript framework to make AJAX-PUSH or real time streaming possible.

cheers! :)

like image 45
varun1505 Avatar answered Nov 15 '22 03:11

varun1505