Home > Software engineering >  I recieve error 419 when trying to post with ajax in laravel
I recieve error 419 when trying to post with ajax in laravel

Time:01-07

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

CodePudding user response:

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.

  • Related