Ajax Request with Laravel 5.4

2

I'm trying to make an example request Ajax with Laravel 5.4 .

The test example is simple, just enter a numeric value in a input=text field in my View and exits the field to send to Controller , then add + 10 to that value and then return this value for my View so it can be displayed in an alert.

HTML : viewteste.blade.php

<!DOCTYPE html>
<head>
    <title></title>
</head>
<body>
    <form action="">      
            Valor: <input type="text" id="valor" name="valor" />
    </form>
  </body>
</html>

JS : The js file is inside viewteste.blade.php, I just separated it to make it easier to interpret.

<script>
    $(document).ready(function(){
       $("#valor").on('blur', function()
       {
           valor = $(this).val();

           var token = $('meta[name="csrf-token"]').attr('content');
            $.ajax({

                type:'POST',
                url:"{!! URL::to('/teste/valor') !!}",
                dataType: 'JSON',
                data: {
                    "valor": 'POST',
                },
                success:function(data){
                    // Caso ocorra sucesso, como faço para pegar o valor
                    // que foi retornado pelo controller?
                    alert('Sucesso');
                },
                error:function(){
                  alert('Erro');
                },
            });


       });
    });
</script>

Route

Route::get('/teste',      'TesteAjaxController@index');
Route::post('/teste/valor', 'TesteAjaxController@valor');

Controller

class TesteAjaxController extends Controller
{
     public function index()
    {
        return view('painel.viewteste');
    }

    public function cep(Request $request)
    {
        $valor= $request->input('valor');
        $valor += 10;
        return $valor; // Como faço para retornar em json? em caso de mensagem de erros?

    }
}

Note : When I left the field and put a test alert on the js function just to see if it is working it will ... and I can display the value the problem is in sending the ajax same. I get in / test and load my view, and when I put / test / value does not display anything, an error appears:

Whoops, looks like something went wrong.
(1/1) MethodNotAllowedHttpException
    
asked by anonymous 30.12.2017 / 22:11

1 answer

1

The error appears because the route has been configured only to accept the verb POST and this will work with its function in , because of its configuration it is for the verb POST equal configured in your route.

If you want this method to work also with other verbos , configure the route file as follows:

Route::match(['get', 'post'], '/teste/valor', 'TesteAjaxController@valor');

So the two types of verbo ( post and get ) will work.

and also has the form to release all verbos :

Route::any('/teste/valor', 'TesteAjaxController@valor');

Note: The correct one is to have a route and a verbo configured for each address, ie only create another route configuration and is configured for that controller and método , but in the

In the you need to put this setting:

<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $(document).ready(function(){
       $("#valor").on('blur', function()
       {
            valor = $(this).val();    
            $.ajax({

                type:'POST',
                url:"{!! URL::to('/teste/valor') !!}",
                dataType: 'JSON',
                data: {
                    "valor": valor
                },
                success:function(data){
                    // Caso ocorra sucesso, como faço para pegar o valor
                    // que foi retornado pelo controller?
                    alert('Sucesso');
                },
                error:function(){
                  alert('Erro');
                },
            });


       });
    });
</script>

31.12.2017 / 15:02