简体   繁体   中英

Gon variable not passing to js from rails controller during Ajax request

I'm trying to create a jackpot betting site (just as a challenge). I have a method in my controller to update the pot when a user adds money to the pot. I display the pot total on the homepage and would like to update it with Ajax as soon as someone adds money to the pot. I'm using the gon gem to pass variables such as the pot total from my controller to my javascript. It works when the page is reloaded but not when the update method is called with ajax.

Heres my PagesController:

def home
  @jackpot = Jackpot.last
  gon.pot = @jackpot.pot
end

JackpotsController:

def update
  @jackpot = Jackpot.find(params[:id])
  if params.has_key?(:amount)
    @jackpot.update(pot: @jackpot.pot + params[:amount].to_f)
    gon.pot = @jackpot.pot
  end
  respond_to do |format| 
    format.js
  end
end

Javascript: (In the url the :id is hardcoded for now)

$("#bet-btn").click(function() {
   $.ajax({
        type: "POST",
        url: "/jackpot/update/21",
        datatype: "json",
        success: function() {
          console.log("Pot size: " + gon.pot);
          updatePot();
        },
        error: function() {
          console.log("error")
        }
    });

});

This updates the donut progress bar for the pot

function updatePot() {
  updateDonutChart('#jackpot-donut', gon.pot , true); 
}

Button to place bet: (amount also hardcoded)

 <%= link_to "Place Bet", update_pot_path(@jackpot, :amount => 
 0.1), method: :post,:remote => true, id: "bet-btn", class: "btn btn-info btn-lg" %>

I'm pretty new to rails and especially javascript/ajax so any help would be appreciated. Thanks!

In the controller, simply respond to JSON:

respond_to do |format|
  format.json { render json: { pot: @jackpot.pot } }
end

Specify the dataType when posting with $.ajax . Notice that the new data is bieng passed to the success function, so it's not gon.pot , but data.pot .

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: function(data) {
    console.log('pot', data.pot);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM