Monday 12 June 2017

Putting live score from database using AJAX and jQuery

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")
        });
});



via Vanshaj Behl

No comments:

Post a Comment