Deejay
Deejay

Reputation: 75

Update using AJAX returns error and going directly to the route shows "MethodNotAllowedHttpException No message"

I am trying to use ajax to update. It always return an error and I don't know where to look. What I'm trying to do is to update without having to reload the page.

VIEW:

    <form id="view-int-form">
    @csrf
        <h1>ID Number:</h1>
        <input type="text" name="id_number" value="{{$var1->id_number}}">

        <h1>Name:</h1>
        <input type="text" name="name" value="{{$var1->name}}">

        <button type="button" id="clickme" value="Save">Save</button>
    </form>

AJAX:

    $(document).on("click", "#clickme", function(){
            $.ajax({
                url: '/updatename',
                type: 'POST',
                data: $("#view-int-form").serialize(), 
                success: function (data) {
                    alert("SAVED");
                },
                error: function (data) {
                    alert("ERROR");
                }
            });
        });

ROUTE:

    Route::post("/updatename","UsersController@UpdateName");

CONTROLLER:

    public function UpdateName(Request $request){
        $id = $request->input('id_number');

        $update_name = $request->input('name');

        users::where("id_number",$id)->update(['first_name'=>$update_name]);        
    }

Thank you to anyone that can help.

Upvotes: 3

Views: 49

Answers (2)

akhil
akhil

Reputation: 106

Its the error with the URL you provided. Its always better to provide URL like below,

url: '{{URL::to('updatename')}}',

Also, you can name your url in web.php like this,

Route::post("/updatename","UsersController@UpdateName")->name('update_name');

then use like this, url:: '{{route('update_name')}}',

Upvotes: 1

Ngoc Tran
Ngoc Tran

Reputation: 69

You are missing {{ csrf_field() }} in form and method="POST" in form tag. Try replace @csrf from your view to {{ csrf_field() }}

Upvotes: 0

Related Questions