1

So I get these numbers from a JSON file:

var homePoints = game.total_points_bet_on_hometeam;
var awayPoints = game.total_points_bet_on_awayteam;

but later on in my code I use an ajax call to submit new numbers and retrieve the new JSON numbers. How would I go about changing homePoints and awayPoints to the new numbers from my ajax call?

I looked over the answers I was given and none of them seem to match what I'm trying to do. Right now the variable that I need to replace the number in is inside another function that is calling the JSON.

         $.each(gameData, function(key, game){
            var homePoints = game.total_points_bet_on_hometeam;
            var awayPoints = game.total_points_bet_on_awayteam;
            var totalPoints = homePoints + awayPoints;

            var myChart = new Chart(ctx, {
                  type: 'doughnut',
                  data: {
                    labels: [homeShort, awayShort],
                    datasets: [{
                      backgroundColor: [
                        homeColor,
                        awayColor
                      ],
                      data: [homePoints, awayPoints]
                    , borderWidth: 0
                    }]
                  },
                  options: {
                        responsive: true
                    ,   maintainAspectRatio: true
                  }
                });
               };

$.ajax({
              url: "---------/dbdata/bet/new/" + userId + "/"+ gameId +"/"+ id +"/"+ value +"",
              type: "get",
            success: function(response) {
                function update(){

                var currentSelection = $('#team-select').val();

                    getGames().done(function(results){
                        $.each(results, function (i, gameData){
                            $.each(gameData, function(key, game){

                                    var gamesId = game.id;

                                    // clears the current bet totals and replaces them with new ones.
                                    if(gameId === gamesId){
                                        var totalPointsHome = this.total_points_bet_on_hometeam;
                                        var totalPointsAway = this.total_points_bet_on_awayteam;
                                        var homePoints = this.total_points_bet_on_hometeam;
                                        var awayPoints = this.total_points_bet_on_awayteam;
                                        var totalPoints = homePoints + awayPoints;

                                        console.log(homePoints)

                                        $('#' + gameId + ' .total-points').empty();
                                        $('#' + gameId + ' .total-points').append( totalPointsAway + totalPointsHome);



                                    }

                            });
                        });
                    })
                }

                update();
  • 1
    This seems like it's a loose duplicate of the standard https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function I'm going to vote on that because I think it's the best answer to this. – Carcigenicate Jan 25 '18 at 22:43
  • 2
    Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Carcigenicate Jan 25 '18 at 22:43
  • 1
    `homePoints = theNewValue;` `awayPoints = aNewValue;`. Maybe a basic javascript programming tutorial is in order here? – gforce301 Jan 25 '18 at 22:43
  • @gforce301 this isn't as simple as you are making it sound. I don't think you understood the question. – Brett Kessler Jan 25 '18 at 22:45
  • @Carcigenicate no that is not what I'm trying to do. – Brett Kessler Jan 25 '18 at 22:46
  • @BrettKessler Pretty sure it is. You're trying to use values from inside of an async callback outside of the callback. That's exactly what the dupe answers. If it doesn't answer your question, you need to explain why and give sufficient context. – Carcigenicate Jan 25 '18 at 22:49
  • @Carcigenicate I added more code to help explain, the var I need to replace is used in the myChart var. – Brett Kessler Jan 25 '18 at 22:57
  • @BrettKessler It still just looks like it's answered by the dupe. Again, aren't you just trying to use the results of an async function from outside of the function? What doesn't the dupe answer? – Carcigenicate Jan 25 '18 at 23:01
  • @Carcigenicate I guess maybe I'm not understanding how to change a var inside of a function from another function.... – Brett Kessler Jan 25 '18 at 23:03
  • Ok this is a design issue/flaw on your part and by the look of it, it's due to a lack of understanding of scope. You're right in that you can't access locally scoped var's from the local scope of another function. So maybe we should just go ahead and reference my first comment. A basic javascript tutorial is in order here so that we can understand how to make reusable code and functions, how to deal with scope issues and like @Carcigenicate said, this is essentially a duplicate. – gforce301 Jan 25 '18 at 23:33
  • @gforce301 can you explain how to make a reusable function to do this? – Brett Kessler Jan 25 '18 at 23:48

1 Answers1

1

@gforce301 can you explain how to make a reusable function to do this?

Sure I'll give it a shot.

Looks like you have some sort of "chart" library you're using and some markup somewhere you're displaying some information in. So lets start by making a variable to hold our "charts" at the global scope and a function to create/update them. Like this:

var charts = {};

function updateChart(game) {
    var chart = charts[game.id],
        homePoints = game.total_points_bet_on_hometeam,
        awayPoints = game.total_points_bet_on_awayteam,
        totalPoints = homePoints + awayPoints;

    // do we have a chart for this game yet? no make one
    if(!chart]) {
        charts[game.id] = new Chart(ctx, {
            type: 'doughnut',

            data: {
                labels: [homeShort, awayShort],
                datasets: [{
                    backgroundColor: [homeColor, awayColor],
                    data: [homePoints, awayPoints],
                    borderWidth: 0
                }]
            },

            options: {
                responsive: true,
                maintainAspectRatio: true
            }
        });
    }
    // yes update the chart
    else {
        // Here is code to update an existing chart which 
        // I know nothing about your charts so you have to write this part
        chart.setSomeProperty('property', value); // <- or however it's done
    }
}

We also need a function to update some markup that I saw some jQuery goodness doing. So let's make that:

function updateMarkup(game) {
    var totalPointsHome = game.total_points_bet_on_hometeam,
        totalPointsAway = game.total_points_bet_on_awayteam,
        homePoints = game.total_points_bet_on_hometeam,
        awayPoints = game.total_points_bet_on_awayteam,
        totalPoints = homePoints + awayPoints;

    $('#' + game.id + ' .total-points').empty();
    $('#' + game.id + ' .total-points').append( totalPointsAway + totalPointsHome);
}

Now that we have that, at the start where we have our initial gameData we just loop it and call our update functions. Like so:

$.each(gameData, function(key, game) {
    updateChart(game);
    updateMarkup(game);
}

Now later on we do some ajax call and get some new game data. We just loop the data and call our update functions again. Like so:

$.ajax({
    url: "---------/dbdata/bet/new/" + userId + "/"+ gameId +"/"+ id +"/"+ value +"",
    type: "get",

    success: function(response) {
        var gameData = response.data // or wherever the data is in the response
        $.each(gameData, function(key, game) {
            updateChart(game);
            updateMarkup(game);
        });
    }
});
gforce301
  • 2,944
  • 1
  • 19
  • 24