I'm trying to submit a form via ajax, but I'm always getting internal server error
Here is my form code
{!! Form::open(['route' => 'users.add', 'id'=>'form']) !!}
<!-- Solo moderador -->
<div class="card-panel">
@if(Auth::user()->permision->request == 1)
<p class="center">Observaciones del moderador:</p>
<textarea type="textarea" class="materialize-textarea" name="observations" id="updateObservations"></textarea>
@else
<div class="center">
<input type="checkbox" id="userVerify" class="filled-in">
<label for="userVerify">Problema solucionado :)</label>
</div>
</div>
@endif
{!! Form::close() !!}
Here is my route
Route::post('request/update', 'RequestsController@postUpdateRequest')->name('request.update');
Here is my Ajax method
$.ajax({
type: "post",
dataType: "html",
url: 'request/update',
data: $("#form").serialize(),
success: function (response) {
// write here any code needed for handling success
console.log("se envio");
}
});
and here is my method in the controller
public function postUpdateRequest(Request $request)
{
if($request->ajax())
{
// Obteniendo registro de la petición
$petition = Petition::where('id', $request->id)->first();
// Guardando
$petition->fill($request->all());
$auditConfirm = $petition->isDirty();
$petition->save();
// Guardando registro de auditoría
if($auditConfirm){
AuditsController::postAudit($this->action_id_update);
}
}
}
Include this in your form:
echo Form::token();
Basically Laravel expects a CSRF token, middleware makes sure that token sent from form matches the token created before it.
If you don't want to add that on forum, you can add that in AJAX setup:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
..and have this in the HTML page header:
<meta name="csrf-token" content="{{ csrf_token() }}">
You are missing the CSRF token, Laravel has a method of handling this vulnerability via middleware, you have 2 options:
{!! Form::open(['route' => 'users.add', 'id'=>'form']) !!} <input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
Provide a global header when making a request:
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
Read more
SOLVED:it seems that ive been missing the id value in the request all this time