AJAX + RAILS Save javascript variable in my database

1

I want to make a game type quiz, that according to the correct answers the user earns X points. Those x points I want to save in a table called Games that has a field called points. I would like to do it without having to do any submit. That is, when the game ends, the score is saved. As a practical example I tried some code but I lost a lot. In the following code I have imagined that the score is always 4, and that when the user clicks on a button, the score 4 is saved in the database.

$(document).ready(function(){
$('#score').on('click',function () {

        alert("hola");
        var score=4;

        Rails.ajax({
                 type: "POST",
                 url: "/games/create",
                 dataType:'json',
                 data: {puntos: score},
                 success: function(msg) {
                     alert("adios");
                     $('#autosavenotify').text("%SDGSFsdfs");
                 }
        })

  });
class GamesController < ApplicationController

  def index
  @games = Game.all

  end

  def new
    @game = Game.new
  end

  def create
@game=Game.new(task_params)

@game.save
  end

  private
    def task_params
      params.require(:game).permit(:puntos)
    end

end
    
asked by ninithblue 02.09.2018 в 18:42
source

1 answer

1

According to me, there are two problems in your code.

The first is that as far as I know, the Rails.ajax method does not exist.

Then there you should do something like $.ajax

And the second thing is that your Controller requires first a :game and then within it allows only :puntos . then something like this should come:

params[:game] = {puntos: "something"}

Look at your code, it should look something like this:

$(document).ready(function(){
  $('#score').on('click',function () {
    var score=4;

    $.ajax({
             type: "POST",
             url: "/games/create",
             dataType:'json',
             data: {game: {puntos: score}},
             success: function(msg) {
                 alert("adios");
                 $('#autosavenotify').text("%SDGSFsdfs");
             }
    })
  });
});

That should work with that, at least the example you have. Now for what you want to do is simply change the event or see how you catch, but in the end, that's it.

I hope it works for you:)

    
answered by 26.09.2018 в 08:03