Necesito pasar datos de jquery (versión 1.9.1) a mi controlador (Laravel 5.1) y luego guardarlos en mysql.
¿Cómo hacer eso y pasar la ranura variable? No funcionó hasta ahora. Para más detalles, por favor me preguntó.
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!"); } }); });Controlador:
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(); }Rutas:
Route::post('/addhistory', 'GameController@addhistory');Errores en la consola:
(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)El archivo 191.js es la versión jquery de 1.9.1
Puedes usar este código, puede funcionar
$(".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; });Prueba este código-
$(".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!"); } }); });Y en su controlador no necesita redirección de retorno porque la solicitud es asíncrona. Así que estoy volviendo verdadero. Asegúrese de incluir el modelo de historial en la parte superior de su controlador
public function addhistory(Request $request) { $game_id=Game::orderBy('id', 'desc')->first()->id; History::create([ 'game_id'=>$game_id, 'moves'=>$request->moves ]); return true; }