TransWikia.com

Ajax returns GET request instead of POST

Stack Overflow Asked by zexar221 on November 24, 2021

I’m trying to create a personal messaging system in laravel, and apart of this system is being able to send messages in a form without refreshing the entire page.

I’ve been following some youtube tutorials, and this is the Ajax script I have so far.

<form id="form{{$dm->id}}">
                    {{ csrf_field() }}
                    <input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
                    <script>
                    $('form{{$dm->id}}').ready(function (){
                        
                    $('form{{$dm->id}}').on('submit', function( event ) {
                        event.preventDefault();
                        $.ajax({
                            type: 'post',
                            url: '{{ route("sendMessage", $dm->id) }}',
                            data: $('form{{$dm->id}}').serialize(), 
                            success: function(response){
                                alert('suces')
                            },
                            error: function(response){
                               alert('failure')
                            }
                        });
                    });
                    });
                    </script>
                </form>

Instead of sending a POST request to the controller, it sends a GET request and just redirects.
This is my first time messing with Ajax/Javascript in general, so I don’t know exactly why this isn’t working.

Controller script:

public function sendM(Request $request, $id)
{
    $validatedData = $request->validate([
        'message' => 'required|string|max:255|min:4',
    ]);
    
    $dm = Dm::find($id);
    $mess = new Message;
    $mess->Authid = Auth::user()->id;
    $mess->Userid = $dm->Userid;
    $mess->Dmid = $dm->id;
    $mess->message = $request->input('message');
    $dm->messages()->save($mess);
    $dm->touch();
}

Route entry:

Route::post('/sendmessage/id{id}', 'SettingsController@sendM')->name('sendMessage')->middleware('verified');

Any help is very much appreciated! (Note: Sorry if it is something really obvious)

3 Answers

An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.

             <form id="form{{$dm->id}}">
                    {{ csrf_field() }}
                    <input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
                    <script>
                    $('form{{$dm->id}}').ready(function (){
                        
                    $('form{{$dm->id}}').on('submit', function( event ) {
                        event.preventDefault();
                        $.ajax({
                            type: 'POST', //Check your JQ version.
                            method: 'POST', //Check your JQ version.
                            contentType:"multipart/form-data; charset=utf-8",
                            //url: '{{ route("sendMessage", $dm->id) }}',
                            url: '{{ route("sendmessage", $dm->id) }}',
                            data: $('form{{$dm->id}}').serialize(), 
                            success: function(response){
                                alert('suces')
                            },
                            error: function(response){
                               alert('failure')
                            }
                        });
                    });
                    });
                    </script>
                </form>

Answered by toto on November 24, 2021

Not sure if it solves your problem, but you must also add the csrf token to the headers:

$.ajaxSetup({
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});

(if the token is in a meta tag of course)

Answered by MrEvers on November 24, 2021

In the $.ajax call, you need to set the method to post instead of the type.

$.ajax({
        method: 'post',
        url: '{{ route("sendMessage", $dm->id) }}',
        data: $('form{{$dm->id}}').serialize(), 
        success: function(response){
          alert('suces')
        },
        error: function(response){
        alert('failure')
        }
       });

As an aside, jquery is often considered to be on the way out. You may want to look into what some alternatives to jquery would look like, such as vue.js or react. Specific to the ajax aspect, Laravel has built in axios support.

Answered by James Clark Developer on November 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP