Update with ajax in laravel

2

I have a project in Laravel and I want to make it when the user type something in the text field, when taking the focus of the field it makes a ajax request to the server to update the information. However I am getting the following error:

MethodNotAllowedHttpException

Javascript:

    $('#table-fases tbody tr td > input').on('change', function() {
        var id = $(this).attr('data-id');
        var titulo = $(this).val();

        $.ajax({
            type: "POST",
            url: 'http://localhost:8000/fases/editar',
            dataType: 'json',
            data: {id: id, titulo: titulo, _token: '{!! csrf_token() !!}'},

            success: function(response) {
                $('#edit-success').append("<div class='alert alert-success'>
                   <button type='button' class='close' data-dismiss='alert'
                                                     aria-label='Close'>
                   <span aria-hidden='true'>&times;</span>
                   </button><strong>Fase editada.</strong></div>");
            } 
        });  
    });

Route:

Route::post('/fases/editar', 'FasesController@update');

Controller:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\FaseRequest;
use App\Pedido;
use App\Fase;
use Session;

class FasesController extends Controller {

    public function index($pedido_id, $codigo) {
        $tituloPedido = Pedido::find($pedido_id);
        $fases = Fase::getFasesPedido($pedido_id);
        return view('fases.index', compact('codigo', 'pedido_id', 'fases', 'tituloPedido'));
    }

    public function salvar(FaseRequest $request) {
        $dados = $request->all();
        $codigo = $dados['codigo'];
        unset($dados['codigo']);

        $fase = new Fase($dados);

        if($fase->save()) {
            Session::flash('success', 'Fase cadastrada com sucesso.');
            return redirect('/pedido/fases/' . $dados['pedido_id'] .  '/' . $codigo);
        }
        else {
            Session::flash('error', 'Problemas ao cadastrar fase. Tente novamente.');
            return redirect('/pedido/fases/' . $dados['pedido_id'] .  '/' . $codigo);   
        }
    }

    public function update(Request $request) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Method: POST, GET, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization");

        $dados = $request->all();

        $fase = Fase::find($dados['id']);

        if($fase->update($dados)) {
            return "success";
        }
    }

    public function delete($id, $pedido_id, $codigo) {
        $fase = Fase::find($id);

        if($fase->delete()) {
            Session::flash('success', 'Fase excluída com sucesso.');
            return redirect('/pedido/fases/' . $pedido_id .  '/' . $codigo);    
        }
        else {
            Session::flash('error', 'Problemas ao excluir fase. Tente novamente.');
            return redirect('/pedido/fases/' . $pedido_id .  '/' . $codigo);
        }
    }

    public function listar_andamento($codigo) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Method: POST, GET, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization");

        $existeCodigo = Fase::existeCodigo($codigo);

        if(empty($existeCodigo)) {
            return 'error';
        }
        else {
            $fases = Fase::getFasesApi($codigo);
            return response()->json($fases);
        }
    }
}

But when I access my route in the browser, the error appears:

MethodNotAllowedHttpException in RouteCollection.php line 218:
    
asked by anonymous 10.02.2018 / 18:46

2 answers

1

The problem of accessing the route by the browser is that the method configured in the route is only for verb POST , but, there is a way that a method responds to most Verb configured or even all example :

Route::match(['get', 'post'], '/', function () {
    //
});

in your case :

Route::match(['get', 'post'], '/fases/editar', 'FasesController@update');

If you want this method to respond to all the Verbs , example :

Route::any('foo', function () {
    //
});

in your case :

Route::any('/fases/editar', 'FasesController@update');

With this change (s) in the configuration method problems not accepted ( MethodNotAllowedHttpException ) did not exist anymore.

Note: The headers methods are unnecessary, you have in addition to the other routes part of your code.

Related links:

Reference: Laravel - Basic Routing

    
11.02.2018 / 13:32
0

If you access the route from the browser it will give this error because the route is of type "POST" and you are trying to access via "GET". If you go through the ajax there will be fine.

You can use a program called POSTMAN to test your routes. He is very good.

    
10.02.2018 / 21:00