AJAX POST request throws "MethodNotAllowedHttpException No message" error right after I submit it

Published 1 week ago by Gabotronix

Hi, I'm trying to make the basic subscription service, sasly laravel is throwing the following error right after I submit the form via AJAX POST request:

 Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message

What could be the cause of this?

Route:

Route::post('/subscripcion', '[email protected]')->name('sub');

JQuery code:

    
    
    
    $(".startSubscription").click(function(){
        var form = $(this).closest('form');
        $('.form_error_text').hide();
        $('.form_valid_text').hide();
        console.log('button start subscription clicked');
        
        var emailval=$("input[name='email']").val();
        
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({
            
            async: true,
            cache: false,
            url: '{{ route('sub') }}',
            type: 'POST',
            data: 
            {
                
            'email': emailval
            
            },
            dataType: 'JSON',
            
            success: function (data) { 
                $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                form.trigger("reset");
                console.log(data.success);
            },
            
            error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
                
                $.each(errors , function(){
                    $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                }); 
            }

        }); 
    });
    

});

My view:

<section class="section_sub_mino_maincontainer" style="width:100%; height:200px; display:flex; flex-direction:column;  justify-content:center; align-items:center; ">
    <form class="section_sub_mino_form_container" method="POST" style="width:auto; height:auto; display:flex; flex-direction:column; align-items:center;">
        <span class="section_sub_mino_form_title" style="font-size:24px; color:rgba(0,0,0,0.7); margin:10px 0px; font-weight:600;">Subscribete para recibir nuestras últimas ofertas, noticias y mucho más</span>
        <div class="section_sub_mino_form_newsletter_container"  style="width:400px; height:40px; outline:1px solid rgba(0,0,0,0.3); display:flex; margin:10px 0px;">
            <input class="section_sub_mino_form_newsletter_input" style="width:80%; height:100%; padding:10px;" type="text" name="email" placeholder="Tu correo electrónico">
            <button class="section_sub_mino_form_newsletter_button startSubscription" style="height:100%; padding:0px 15px; font-size:18px; text-transform:uppercase; display:flex;background-color:var(--web_primary_color); color:white;  align-items:center; ">SUBSCRIBIRME</button>
        </div>
        <div class="form_valid_container"></div>
        <div class="form_error_container"></div>
    </form>
</section>

Controller:

<?php

namespace App\Http\Controllers;

use App\Emails;
use Illuminate\Http\Request;
use App\Http\Requests\StoreSubbedMail;

class SubscriptionController extends Controller
{
    
    
    
    
    public function index()
    {
        //
    }

    
    
    
    public function create()
    {
        //
    }

    
    
    
    public function store(StoreSubbedMail $request)
    {
        $email = new Emails();
        $email->subbed_mail = $request->email;
        $email->save();
        
        return response()->json(['success'=>'Te subscribiste correctamente!'], $email);
    }

Form request:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreSubbedMail extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'subbed_mail' => 'required|email|unique:emails',
        ];
    }
}
Cronix
Cronix
1 week ago (566,300 XP)

do you have any other routes with the name of sub?

Gabotronix

No, these are all my routes:

Route::get('/', '[email protected]');

Route::get('/nuestra-carta-de-menus', '[email protected]');

Route::get('/localizacion', '[email protected]');

Route::get('/horario-de-apertura', '[email protected]');

Route::get('/contacta-con-nosotros', '[email protected]');

Route::get('/contactar/hacer-una-reserva', '[email protected]');

Route::get('/contactar/trabaja-con-nosotros', '[email protected]');

Route::get('/opiniones-de-nuestros-clientes', '[email protected]');

Route::get('/diseños', '[email protected]ños');

Route::get('/panel-de-administrador', '[email protected]');//->middleware('auth')

//Contact mail routes

Route::post('/contactar-mail-simple', '[email protected]');

Route::post('/contactar-mail-avanzado', '[email protected]');

//Resource routes 

Route::resource('globals','GlobalsController');

Route::resource('posts','PostController');

Route::resource('sliders','SliderController');

Route::resource('reviews','ReviewController');

Route::post('/subscripcion', '[email protected]')->name('sub');


//Authentication Routes...

Route::get('login', 'Auth\[email protected]')->name('login');
Route::get('/logout', '\App\Http\Controllers\Auth\[email protected]');
Route::post('login', 'Auth\[email protected]');
Route::post('logout', 'Auth\[email protected]')->name('logout');

//Registration Routes...

//Route::get('register', 'Auth\[email protected]')->name('register');
//Route::post('register', 'Auth\[email protected]');

//Password Reset Routes...

Route::get('password/reset', 'Auth\[email protected]')->name('password.request');
Route::post('password/email', 'Auth\[email protected]')->name('password.email');
Route::get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset');
Route::post('password/reset', 'Auth\[email protected]');
Cronix
Cronix
1 week ago (566,300 XP)

Is your javascript a separate standalone js file, or is it a part of the view?

When you look at your dev tools in the browser when submitting the ajax request (network tab), is it going to yoursite.com/subscripcion?

Also, what are you clicking on with class of startSubscription to trigger all of this?

Gabotronix

I updated OP with my view, also just checked the network tab and the POST request is being sent to http://127.0.0.1:8000/ with a status code of 405, it's not being sent to my route... weird

Also my js code is a separate file

jlrdw
jlrdw
1 week ago (226,270 XP)

Try

    url: 'sub',
    // or
    url: '/sub',
Gabotronix

I tried with /sub and the request was sent BUT I'm still getting the same exception thrown, after checking network tab it appears there's ANOTHER POST request, this is the one wich is giving me the error for sure.

Problem is I have no idea what is sending that request??

https://i.imgur.com/8itW66M.png

How can I know where that request comes from?

Cronix
Cronix
1 week ago (566,300 XP)

Also my js code is a separate file

That's why.

url: '{{ route('sub') }}',

You're using blade syntax, which is parsed by laravel, as well as using route(), which is also php, which you can't use in js files. .js files don't go through laravel or parsed by php. So you can only use pure javascript in them.

So just use the actual url from your route and don't use any php.

url: '/subscripcion'

Another thing you should do is cancel the native click event on that button. You might be sending your form and also triggering the ajax request. And since the form doesn't have an action attribute to submit to, it submits to the current url.

$(".startSubscription").click(function(e){ // add e
    e.preventDefault(); // prevent default click event on button
// rest as it is...
Cronix
Cronix
1 week ago (566,300 XP)

/sub obviously wouldn't work, as that also only works when using route() since it's a name and not an actual endpoint. You need to use the defined http endpoint, /subscripcion

Route::post('/subscripcion', '[email protected]')->name('sub');
jlrdw
jlrdw
1 week ago (226,270 XP)

I was going off of what OP showed in their Ajax

url: '{{ route('sub') }}',
hiayongkuy

have you check the CSRF in your ajax?

https://laravel.com/docs/5.6/csrf

Cronix
Cronix
1 week ago (566,300 XP)

@Gabotronix Did you get this working? It looks like it since you've started a different post about it with a different problem. Please mark as solved.

Please sign in or create an account to participate in this conversation.