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>
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
Related
So I'm having a database which gets updated after getting score of a match.
Right Now I'm able to make ajax get request to my route for getting the latest score from database on $(document).ready(function() and change my html to show score but it is static and does not gets updated.
So my question is how to make this ajax request in a loop. Right now a user has to refresh to make the request again and get the updated latest score.
I am using mongoose, mongodb, nodejs on express framework, and jquery for scripts.
This is my nodejs route for handling ajax request, it returns json of match data
router.get('/matchData',function(req,res){
Match.getMatchData(function(err,match){
if(err) throw err;
res.send(match);
});
});
This is my script for AJAX.
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'http://localhost:3000/matchData',
dataType: 'json'
})
.done(function(data) {
$('.team1').text(data.title);
$('.team1odds').text(data.values.t1odds);
$('.team1probability').text(data.values.t1probability);
$('.team1score').text(data.values.t1predict);
$('.team2').text(data.title);
$('.team2odds').text(data.values.t2odds);
$('.team2probability').text(data.values.t2probability);
$('.team2score').text(data.values.t2predict);
})
.fail(function() {
alert("Ajax failed to fetch data")
});
});
There are multiple ways to do this, the easiest would be to use long polling, but it is also the most ineffective.
Very simple example:
var seconds = 5;
setInterval(function runner() {
// run your ajax call here
var result = callAjax();
}, seconds * 1000);
A much better way would be to use websockets, as the score gets updated server-side you push the event to the client.
I know we can make a javascript ajax request from some server and it either receives the response or gives timeout error after some time.
Let's consider this scenario when we don't want to wait for the request rather the server would send a response(or we can say it would be another request from server to client) async at any time after getting the request and then call a javascript CB function with the response.
I am looking for ideas for how to go about it mainly supporting all modern browsers and if possible not relying on any 3rd party plugin except may be jQuery.
The main feature of Ajax is that it IS asynchronous by default, and your program will continue to run without waiting for the response. So unless I'm misreading your question, it is what you need.
If you use jquery, then you pass in a callback function that will execute only when the server sends back a response. You can specify a timeout in the settings, though I'm not sure what the maximum time you can provide without getting a timeout error. But it will be several seconds, at least.
You can even specify different callbacks for success and fail as follows (adapted from the jquery ajax API, but added a timeout of 5 seconds):
var request = $.ajax({
url: "http://www.some.url/",
method: "GET",
data: { some : stuff },
dataType: "html",
timeout: 5000
});
request.done(function( data ) {
console.log( "SUCCESS: " + data );
});
request.fail(function() {
console.log( "Request failed");
});
I came across this question after 4 years. I dont remember in what context I asked this but for anyone who has the same query:
Http is a request/response protocol. Which means the client sends a request and the server responds to that request with some message/data. Thats the end of the story for that request.
In order for the server to trigger something on the clientside we will have to use something that keeps the connection to the server rather than ending the communication after getting the response. Socket.io is bi directional event driven library that solves this problem.
To update a cart (PHP Session storage and reserve the stock of items in database) on my online shop, I simply add a timeout of 100ms after calling it and remove Success/Error callback.
$.ajax({
url: 'http://www.some.url/',
method: 'GET',
data: {
some : 'stuff'
},
dataType: 'html',
timeout: 100
});
Note : It doesn't matter if some requests didn't arrive, because when the order is saved, an update of the whole cart is sent with a callback.
If your query needs acknowledge, don't use that solution !
I believe your question is similar to this
by Paul Tomblin. I use the answer provided by gdoron, which is also marked as the best solution, and also the comment by AS7K.
$.ajax({
url: "theURL",
data: theData
});
NB: No async parameter provided.
I'm trying to send Ajax request using jquery and HTML5.
I have several pages in my application.
Is it possible to make Ajax request on a page(e.g sync.html) and receive response on a different page(e.g home.html).
I know there are other approaches to this like web-sockets and long pooling but if it's possible to achieve this using Ajax then that will make my work easier preventing me from changing any server configurations.
I'm using ASP.NET,C# on the server side.
The reason why I'm doing this is to prevent users from waiting for the response before they resume doing any other activity because this might take long depending on the size of data sent to server and the internet speed.
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: server_url,
data: {
number_chunksdone : num_chunksdone,
sync_data: round_1_sync_data,
organisation_id: organisation_id,
sync_id: sync_id,
instrument_id: instrument_id,
user_id: user_id,
sync_data_2: round_2_sync_data
},
success: function (j) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
Any idea?
You can try writing Location.replace() or Location.assign() method inside success function. For e.g., document.location.replace('home.html');
The Location.replace() method replaces the current resource with the one at the given URL.
I wanted to use long polling.
I google it and found many helpful resources, and since many, I am getting confuse which is better.
Following are three code snippets from two place.
https://gist.github.com/jasdeepkhalsa/4353139
// Long Polling (Recommened Technique - Creates An Open Connection To Server ∴ Fast)
(function poll(){
$.ajax({
url: "server",
success: function(data)
{
//Update your dashboard gauge
salesGauge.setValue(data.value);
},
dataType: "json",
complete: poll,
timeout: 30000
});
})();
// The setTimeout Technique (Not Recommended - No Queues But New AJAX Request Each Time ∴ Slow)
(function poll(){
setTimeout(function(){
$.ajax({
url: "server",
success: function(data)
{
//Update your dashboard gauge
salesGauge.setValue(data.value);
//Setup the next poll recursively
poll();
},
dataType: "json"});
}, 30000);
})();
https://github.com/panique/php-long-polling/blob/master/client/client.js
function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp};
$.ajax(
{
type: 'GET',
url: 'http://127.0.0.1/php-long-polling/server/server.php',
data: queryString,
success: function(data){
// put result data into "obj"
var obj = jQuery.parseJSON(data);
// put the data_from_file into #response
$('#response').html(obj.data_from_file);
// call the function again, this time with the timestamp we just got from server.php
getContent(obj.timestamp);
}
}
);
}
My question is which code is long polling best practice?
Which one should I use?
Thanks in advance.
The first approach is better on my opinion:
If server configured for long polling with timeout more than 30000, then with first one you will have breaking request by timeout and a new request will be sent, success() function would not be called
(while complete() will be, also error could be handled in error() like this
error: function(x, t, m) {
if(t==="timeout") {
alert("got timeout");
} else {
alert(t);
}
}
).
While in the second one a new request would be sent after 30000 and so you would have unpredictable behavior on a client side (two requests can receive the same answer, so data could be duplicated).
If server configured for long polling with less than 30000, then in second approach data on a client side would not be updated in time.
If server configured for long polling with 30000, then it should not be any difference.
To summarize: in first approach situation is controllable, while in second one - not always.
I am working on new app in javascript. What I need is that whenever latest news is added to the database at the backend then the front end should know about it and update that area asynchrnously. What is the best and efficient way to achieve this in JavaScript and/or jQuery?
I would recommend using long polling. With a quick Google search you should be able to get up and running. For example here.
use Window.setInterval() to reload the page for specific interval of time so that the news gets updated
$.ajax Documentation
make a function get_news which contains ajax request which well get updated content from the server.
setInterval(get_news, 1000) will call the function get_news after every 1000 ms
function get_news() {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$('#content').html(data);
}
dataType: dataType
});
}
setInterval(get_news, 1000); //1000 ms