A simple example of a long survey with javascript and jQuery

I am trying to create a real-time website analytics dashboard that creates an open HTTP connection to a server using jQuery / JavaScript asynchronous launch to poll the server to update the data as it occurs.

An obvious start for this would be to use the XMLHttpRequest or jQuery $.ajax to send a GET or POST to a server that asks for some data asynchronously.

However, without sending one request at a time using the setInterval method every 30 seconds , I'm not sure how to make the connection to the server permanent. Basically, I want to send one http request and make sure that the connection to the server remains open for polling!

My sample code with setInterval 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> 
+4
source share
1 answer

After searching the web, this was the answer I was looking for that does not use sockets.io and WebSockets but uses jQuery , using 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> 

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

+12
source

All Articles