Methodnotallowedhttpexception($others) Laravel Send form via Ajax

Asked

Viewed 218 times

1

I have a simple form and I am sending it to the controller by Ajax, but my problem is that after clicking the Submit button it does not call the Ajax request in my Jquery and already forwards straight to this error.

Erro ao dar submit no formulário

I have another controller and copied all the process changing only the inputs and fields

Javascript code the system should pass after submit

 jQuery("#formRecebimento").submit(function(){
            var dados = jQuery( this ).serialize();            
            jQuery.ajax({
                type: 'post',
                url: 'recebimentos/cadastrar',
                data: dados,
                beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', $("#token").attr('content'));},                
                success: function(data) {
                    if($.isEmptyObject(data.error)){
                        alert(data.id);                        
                        $('#modalAddCliente').modal('hide');

                    }else{
                        printErrorMsg(data.error);
                    }
                }


            });

            return false;
    });

But he doesn’t even get to that part of the code!

PS: IN ANOTHER CONTROLLER I MOUNTED THE SAME WAY AND WORKED CORRECTLY

ROUTES

$this->group(['prefix' => 'recebimentos'], function(){
    $this->post('cadastrar', 'RecebimentoController@store');
    $this->post('atualizar', 'RecebimentoController@update');
    $this->post('detelar', 'RecebimentoController@destroy');

    $this->get('/', 'RecebimentoController@index');
});

CONTROLLER PS: INDEX IS WORKING NORMALLY AND I LEFT THE STORE COMMENTED TO FIND WHERE THE ERROR IS AND IT DOESN’T EVEN ARRIVE IN MY CONTROLLER

public function store(Request $request){      /*
         $validator = Validator::make($request->all(), [
            'data_receb' => 'required|date|after:start_date',
            'valor' => 'required',
            'cliente_id' => 'required',
            'plano_contas' => 'required|max:100',                  
        ]);
        if ($validator->passes()) {

            $recebimento = Recebimento::create($request->all());
            return response()->json($recebimento);
        }
        return response()->json(['error'=>$validator->errors()->all()]);      */  

        return "asefa";
    }

PART OF THE DEFINITION OF THE FORM

<form id="formRecebimento" method="post">

                            <input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
                            <div class="row">
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="data_receb">Data do Recebimento*</label>
                                            <input type="date" class="form-control data_receb" id="data_receb" name="data_receb" >
                                        </div>
                                    </div>

SCRIPT GLOBAL PS: I HAVE A JS FILE FOR EACH CONTROLLER

$.ajaxSetup({
                headers: {
                    'X-XSRF-Token': $('meta[name="_token"]').attr('content')
                }
            });

1 answer

1


You are not handling the Submit event in jquery correctly.

What’s going on is:

When you click the form send, it triggers the Submit event, Jquery picks up this bad event by default it continues (with the form action attribute) and not with the ajax you created.

How To Solve:

the right thing for you to do is to block this "default" and deal with it within the $('#form').submit();

Just do this:

jQuery("#formRecebimento").submit(function(e){
    e.preventDefault();
    //Resto do Código
});

Why use Preventdefault?

Why it cancels the event if it is cancellable, without stopping the spread of the same.

In this case it continues in the <form> But who controls this is his JS code

Some References:

https://stackoverflow.com/a/6960586/7705942

https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

Browser other questions tagged

You are not signed in. Login or sign up in order to post.