0

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

Christian
  • 61
  • 6
  • 1
    You probably did not add the @csrf code in your form data, so the token expected from your form is not present. – DreamBold Jan 06 '23 at 16:21
  • 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` – UnderDog Jan 06 '23 at 16:27
  • https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request Hope it helps! – DreamBold Jan 06 '23 at 16:28
  • 1
    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 `
    ` 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](https://stackoverflow.com/posts/75033430/edit) and include `formData` if you need more info.
    – Tim Lewis Jan 06 '23 at 16:34
  • Yeah sorry,Im new to ajax and laravel,I'll put all of the code,thought it wasn't so important – Christian Jan 06 '23 at 16:42
  • 1
    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. – Tim Lewis Jan 06 '23 at 16:59

1 Answers1

4

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.