Reputation: 143
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")
});
});
Upvotes: 0
Views: 1595
Reputation: 16615
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.
Upvotes: 1