I created a form and I try onsubmit to send the data to the database without any redirect,this is my code so far:
Jquery:
jQuery(function() {
$("#save").on("submit",function(event){
var formData = {
name: $("#name").val(),
size: $("#email").val()
};
if($("#id").length != 0)
formData['id'] = $("#id").val();
$.ajax({
type:"POST",
headers: {'X-CSRF-TOKEN': $('input[name="_token"]').val()},
url: "/drawingSave",
data: formData,
dataType:"json",
encode:true,
}).done(function(data){
console.log(data.data['name']); //printing the name to check if it worked
});
event.preventDefault();
});
$("[data-toggle='popover']").popover();
});
this is the form:
<form id="save" method="POST">
@csrf
<input oninput="ChangeInput(this.value)" value="{{$data['name'] ?? 'canvas'}}" type="text" name="name" id="name">
<input type="hidden" name="size" id = "size" value="{{$data['size']}}">
@isset($data['id'])
<input type="hidden" name="id" id="id" value="{{$data['id']}}">
@endisset
<button type="submit">Save</button>
<button type="submit">Save</button>
</form>
this is the route:
Route::post('drawingSave',[DrawingController::class,'save']);
and this is the function in the controller:
public function save(Request $request){
$data = $request->all();
// checks if the drawing exists
if(is_null($request->id))
{
$data['users_id'] = Auth::id();
$check = $this->create($data); //if not creates new Drawing model
}
else
{
$check = Drawing::where('id','=',$data['id'])->update([
'name' => $data['name'],
'canvas_size' => $data['size']
]); //updates the current one
}
return response()->json([
'data' => $data
]);;
}
I recieve the 419 error
Edit:I added the line(headers: {'X-CSRF-TOKEN': $('input[name="_token"]').val()},) in the $.ajax but now I get the error 500
Edit2:I found a typo in the code,now everything is working,thanks
jquery ajaxsetup csrf token
... //setting the data
, ends up being kinda the most important part (somewhat; there's multiple ways to get the csrf
token into an AJAX request). If formData
is a serialization of the <form>
element, this should work on it's own, but if you're manually constructing formData
as an Object { field: 'value', ... }
, then you likely just forgot to include it. You've got an answer, but you can also edit your question and include formData
if you need more info. formData
is an object, you simply missed it: var formData = { _token: $('input[name="_token"]').val(), name: $("#name").val(), size: $("#email").val() };
. Also, if your code is throwing a 500 error now, try to debug it first (check the error in storage/logs/laravel.log
), and ask a new question if you can't figure it out. A 419 error
indicates you're not passing through your csrf
token.
You can set the value of this in the header
of your ajax
headers: {'X-CSRF-TOKEN': $('input[name="_token"]').val()}
This is because @csrf
is rendered as <input type="hidden" name="_token" value="{{ csrf_token() }}" />
in the DOM.