Home > Enterprise >  Laravel Ajax request throwing MethodNotAllowedException with post method
Laravel Ajax request throwing MethodNotAllowedException with post method

Time:11-22

I am new to the Laravel and I am trying to submit post data via Ajax in Laravel and it throws

MethodNotAllowedException but when I submit the form via post it does work but refresh the page although I have used Ajax.

my Code is as below:

My JavaScript Ajax code:

function collect(){
    
    $.ajaxSetup({
        headers:{
            'X-CSRF-TOKEN': $("input#token").val()
        }
    });




    const   user = [{"fname": $("input#fname").val(), _token: $("input#token").val(), _method:"POST", "lname": $("input#lname").val(),
                "email": $("input#email").val(), "pass": $("input#pass").val(),
                "confirm-pass": $("input#confirm-pass").val() 
     }];

     var form = $('form#add-user-form');

     var send_button = $('button#send').text();
     $.ajax({
        url: '/users/store',
        method: 'post',
        data: user,
        processData: false,
        dataType: 'json',
        contentType: false,
        beforeSend:function(){
                $(form).find('span.error-text').text('');
                
        },
        success:function(data){
            alert('data sent');
            
            if (data.code == 0 || data.status == 400 ){
                $.each (data.error, function(prefix, value){
                    alert(prefix   '   '   value[0]);
                    $(form).find('span.' prefix '_error').text(value[0]);
                });
            }else {
                
                $(form)[0].reset();
                alert(data.msg)
            }
            

        }

     });

    

   }  

--- Controller Code ------------------------

$validator = \Validator::make($request -> all(), ['fname' => 'required|min:5|max:25', 
                        'lname' => 'required|min:5|max:25',
                        'email' => 'required|email|unique:users', 
                        'pass' => 'required|min:8|max:20|', 
                        'confirm-pass' => 'required|min:8|max:20'
                        ]);

    if (!$validator -> passes() ){
        return response()->json(['code'=> 0, 'error'=> $validator->errors()->toArray()]);
    }else {
            $user = new users();
            $user -> name = $request -> fname ;
            $user -> email = $request -> email ;
            $user -> password = $request -> pass;
            $query = $user -> save();
            if ( !$query ){
                return response() -> json(['code'=> 0, 'msg' => 'something went wrong']);
            }else {
                return response() -> json(['code' => 1, 'msg' => 'users has been successfully 
                 added']);
        

--------------- HTML Code which -------------

<div id="registeration-form">

    <div id="form-holder container">

        <form action="{{ route('users.store') }}" method="post" class="registration needs-` 
        validation" id="add-user-form">
                     
                    <input type="text" class="form-control" id="fname"  name="fname" placeholder=" 
                    First Name" required> </input>
                    <span class="text-danger error-text fname_error"></span>
                    <input type="text" id="lname" class="form-control" name="lname" placeholder=" 
                     Last Name " required> </input>
                    <span class="text-danger error-text lname_error"></span>
                    <input type="text" class="form-control" id="email" name="email" 
                     placeholder="Your Email " required> </input> 
                    <span class="text-danger error-text email_error"></span>
                    <input type="password" class="form-control" id="pass" name="pass" 
                     placeholder="Password " required> </input>
                    <span id="text-danger error-text pass-span pass_error"> </span>
                    <input type="password" class="form-control" id="confirm-pass" name="confirm- 
                     pass" placeholder="Confirm Password " required> </input>
                    <span id="text-danger error-text con-pass confirm-pass_error"> </span>
                    <input type="hidden" id="token" name="_token" value="{{ csrf_token() }}" />
                    <button type="button" class="btn btn-outline-primary" id="send" 
                    onClick="collect();">Create Account </input>

           </form>
        
      </div>

  </div>

My Route web.php file

Route::post('/store', 'usersController@store');
Route::post('store',[usersController::class, 'store'])->name('users.store');

What I want is that the Ajax should work without page refresh and

     > it does through MethodNotAllowedException  Line 251

CodePudding user response:

Thank you all for your cooperation in this matter, I have resolved this issue with below changes.

  1. I have added a route in route/api.php

    Route::post('store', [usersController::class,'store']);


  1. I have changed my Ajax sent url as below.

    url: $('form#add-user-form').attr('action'),

That worked for me to resolve the issue.

@steven7mwesigwa Thank you for your answer, it was really helpful.

CodePudding user response:

The route below doesn't exist.

$.ajax({
    // ...
    url: '/users/store',
    // ...
});

Use this instead: Note that you don't have to construct the data manually.

$.ajax({
    // ...
    type: form.attr("method"),
    url : form.attr("action"),
    data: form.serializeArray(),
    // ...
});

NOTES:

  1. Note that the 2 routes are the same:
Route::post('/store', 'usersController@store');
Route::post('store',[usersController::class, 'store'])->name('users.store');

You may want to remove one of them. If you're working with Laravel 8 and above, the format used in the second one is preferable.

  1. Though not necessary, you may want to include the HTML markup below in your form as well. The value sent with the _method field will be used as the HTTP request method.
<input type="hidden" name="_method" value="POST">
  1. I believe you have mismatching HTML tags on your submit button.
<button type="button" class="btn btn-outline-primary" id="send" 
                    onClick="collect();">Create Account </input>
  1. To avoid page reload. pass the event to the method call. In addition, prevent the default behaviour from your method definition.
<!-- HTML code. -->

<button type="button" class="btn btn-outline-primary" id="send" 
                    onClick="collect(event);">Create Account </button>
// JavaScript Ajax code.

function collect(event){

    event.preventDefault();

    $.ajax({

        // ...

    });

    // ...

}

CodePudding user response:

You must provide route for ajax request into route/api.php

CodePudding user response:

use this instead of your current ajax configs:

    url: '{{route('users.store')}}',
    type: 'post',
    data: user,
    processData: false,
    dataType: 'json',
    contentType: false,

first of all it's better to use blade routes instead of writing the url, and secondly it's "type" not "method" when you're trying to use POST method in ajax

  • Related