Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.

How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.

jquery:

 $(".tic").click(function(){
    var slot = $(this).attr('id');
    playerTurn(turn, slot);
    $.ajax({
        url: '/addhistory',
        type: 'POST',
        data: { _token: {{ csrf_token() }}, moves: slot },
        success: function()
        {
            alert("Data has been saved successfully!");
        }
    });
 });

Controller:

 public function addhistory(Request $request)
    {
        $history = new History();
        $history->game_id = Game::orderBy('id', 'desc')->first()->id;
        $history->moves = $request->moves;
        $history->save();
        return redirect()->back();
    }

Routes:

Route::post('/addhistory', 'GameController@addhistory');

Errors in console:

(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
    at HTMLAnchorElement.<anonymous> ((index):198)
    at HTMLAnchorElement.dispatch (191.js:3)
    at HTMLAnchorElement.v.handle (191.js:3)

191.js file is the jquery version of 1.9.1

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can use this code, it may works

 $(".tick").click(function (event) {
    event.preventDefault();
    $('.loading').show();
    var form = $(this);
    var data = new FormData($(this)[0]);
    var url = form.attr("action");
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
           alert("Data has been saved successfully.");
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
    return false;
});
about 4 years ago · Santiago Trujillo Relatório

0

Try this code-

$(".tic").click(function(){
  var slot = $(this).attr('id');
  var token= $("input[name='_token']").val();
  playerTurn(turn, slot);
  $.ajax({
      url: '/addhistory',
      type: 'POST',
      data: { '_token': token, 'moves': slot },
      success: function()
      {
          alert("Data has been saved successfully!");
      }
  });
});

And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller

 public function addhistory(Request $request)
    {
        $game_id=Game::orderBy('id', 'desc')->first()->id;
        History::create([
                        'game_id'=>$game_id,
                        'moves'=>$request->moves
        ]);
        return true;
    }
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda