menu

Questions & Answers

I recieve error 419 when trying to post with ajax in laravel

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

Comments:
2023-01-07 20:33:12
You probably did not add the @csrf code in your form data, so the token expected from your form is not present.
2023-01-07 20:33:12
You're sending an Ajax request, so in your $ajaxSetup, yes, you should send the csrf token. Sending it in the form itself doesn't make sense. Search keywords for google: jquery ajaxsetup csrf token
2023-01-07 20:33:12
2023-01-07 20:33:12
I find it a little funny that the only part of this question you omitted, ... //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.
2023-01-07 20:33:12
Yeah sorry,Im new to ajax and laravel,I'll put all of the code,thought it wasn't so important
2023-01-07 20:33:12
So yeah, since 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.
2023-01-07 20:33:12
okay,thanks a lot!
Answers(1) :

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.

Comments:
2023-01-07 20:33:12
I added this and the 419 error solved,now it is error 500 for some reason
2023-01-07 20:33:12
@Christian for 500 error , check your laravel.log
2023-01-07 20:33:12
Yes,I found the error,It was a typo,thanks anyway