Update with ajax in Laravel

Asked

Viewed 898 times

2

I have a project in Laravel and I want to make sure that when the user type something in the text field, when taking the focus of the field he makes a request ajax to the server to update the information. However I am receiving 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 accessing my route in the browser the error appears:

MethodNotAllowedHttpException in RouteCollection.php line 218:
  • Put the controller

  • I put the contents of the controller.

  • It has to be complete

  • I put the whole controller.

  • And then it worked?

  • Oops. Good morning! Sorry for the delay, man. It worked. Thank you :)

  • If you can tick as the answer to the question

Show 2 more comments

2 answers

1


The problem of accessing the route by the browser is that the method configured on the route only serves for Verb POST, but, there is the way a method responds to more Verb configured or up to all, example:

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

in your case:

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

If you want this method to answer all Verbs, example:

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

in your case:

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

with this change(s) in the configuration the method problems not accepted (MethodNotAllowedHttpException) no longer existed.

Observing: the headers in the methods are unnecessary, has in addition to the part of routes other problems in your code.

Related links:

Reference: Laravel - Basic Routing

0

If you access the route from the browser will give this error because the route is of type "POST" and you are trying to access via "GET". If you access by ajax there will occur all right.

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

Browser other questions tagged

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