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

6
  • 1
    You probably did not add the @csrf code in your form data, so the token expected from your form is not present. Commented Jan 6, 2023 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 Commented Jan 6, 2023 at 16:27
  • stackoverflow.com/questions/32738763/… Hope it helps! Commented Jan 6, 2023 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 <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. Commented Jan 6, 2023 at 16:34
  • 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. Commented Jan 6, 2023 at 16:59

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I added this and the 419 error solved,now it is error 500 for some reason
@Christian for 500 error , check your laravel.log
Yes,I found the error,It was a typo,thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.