Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple long polling example with JavaScript and jQuery

I'm trying to create a real-time website analytics dashboard which creates an open HTTP connection to the server using jQuery/JavaScript asynchronously to poll the server for updates to the data as and when they occur.

The obvious start for this would be to use an XMLHttpRequest object or jQuery's $.ajax method to send a GET or POST request to the server asynchronously requesting some data.

However, beyond sending one request at a time using a setInterval method every 30 seconds I am not sure how to make the connection to the server persistent. Basically, I only want to send one http request and ensure the connection to the server stays open for polling!

My example code with setInterval is as follows:

<div id="analytics"></div>
<script>
var analytics = document.getElementById('analytics');
setInterval(function(){
    $.ajax({ url: "http://server.com/", success: function(data){
        analytics.innerHTML = data;
    }, dataType: "json"});
}, 30000);
</script>
like image 267
technojas Avatar asked Dec 25 '12 01:12

technojas


1 Answers

After searching online, this was the answer I was looking for which doesn't use sockets.io nor WebSockets but does use jQuery by taking advantage of its complete method to create an artificial loop:

<div id="analytics"></div>
<script>
var analytics = document.getElementById('analytics');
(function poll(){
    $.ajax({ url: "server", success: function(data){
        analytics.innerHTML = data;
    }, dataType: "json", complete: poll, timeout: 30000 });
})();
</script>

Source is Tian Davis from Technoctave: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery

like image 50
technojas Avatar answered Nov 17 '22 12:11

technojas