Home > OS >  ajax api and check if data is newer then previous call
ajax api and check if data is newer then previous call

Time:09-18

I'm checking an api for some NFL scores , but the data is not always newer than the previous request I've made.

Site owner has no time to fix the issue. I check the API every 10 seconds and I keep getting old items. The api is only updated when NFL games are live , so you can't actually see the issue until then , but opening the link in your browser and refreshing you see the data is always retrieving old and new . Is there a easy way to fix this on my end ?

$.ajax({
    url: 'https://api.myfantasyleague.com/2022/export?TYPE=nflSchedule&W=&JSON=1',
    type: "GET",
    dataType: 'json',
    success: function (data) {
        if (data.hasOwnProperty("error")) {
            console.log("No Schedule Exists")
        } else {
            // if data is old - do nothing
            // id data is new then proceed
            console.log(data)
        }
        data = null;
    }
});

during live games , all the items jump back and fourth from older to current/new

{"kickoff":"1663287300","gameSecondsRemaining":"0","team":[{"inRedZone":"0","score":"24","hasPossession":"0","passOffenseRank":"4","rushOffenseRank":"24","passDefenseRank":"19","spread":"3.5","isHome":"0","id":"LAC","rushDefenseRank":"10"},{"inRedZone":"0","score":"27","hasPossession":"0","passOffenseRank":"7","rushOffenseRank":"15","passDefenseRank":"21","spread":"-3.5","isHome":"1","id":"KCC","rushDefenseRank":"13"}

CodePudding user response:

I'm not sure how you are displaying this data, but lets say you have a Div for each game..

When you update the information save the gameSecondsRemaining as an attribute in the Div / container

$.ajax({
    url: 'https://api.myfantasyleague.com/2022/export?TYPE=nflSchedule&W=&JSON=1',
    type: "GET",
    dataType: 'json',
    success: function (data) {
        if (data.hasOwnProperty("error")) {
            console.log("No Schedule Exists")
        } else {

            // if data is old - do nothing
            if ( // if container has attribute && attr is newer
                $("#game1container").attr('gameSecondsRemaining') && 
                data['gameSecondsRemaining'] >= parseFloat($("#game1container").attr('gameSecondsRemaining'))){
                return
            };

            // else:
            // process data
            $("#game1container").find('.score').html(data['team1']) // or idk
            // etc

            // store time associated with loaded data
            $("#game1container").attr('gameSecondsRemaining', data['gameSecondsRemaining']);
        }
        data = null;
    }
});
  • Related