2

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
2
  • I have resolved the problem just by getting the path from the form. via this line of code $.ajax({ url: $('form#add-user-form').attr('action'), method: 'post', ... Commented Nov 21, 2021 at 8:49
  • Great that you figured it out. I actually noticed that earlier already in my answer.😉 stackoverflow.com/a/70052884/7376590 Commented Nov 21, 2021 at 9:00

4 Answers 4

1

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.

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

Comments

0

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

4 Comments

could you please give me an example of a route that how can I add ?
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Let Laravel handle ajax URL for you. use {{route('users.store')}} in your ajax URL. It probably solve your problem.
@Hadem you just move the contents of file routes/web.php to routes/api.php, or if not works you can try the solution from @Mehdi Hosseini
0

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

Comments

0

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({

        // ...

    });

    // ...

}

Comments

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.