Ajax Request with Laravel 5.4

Asked

Viewed 2,714 times

2

I’m trying to perform an example of requisition Ajax with the Laravel 5.4.

The example for testing is simple, just enter a numerical value in a field input=text in my View and leaves the field to send to the Controller, then it is added + 10 to that value and then returns that value to my View so that 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 : js file is inside viewteste.blade.php, I just separated it to make the interpretation easier.

<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?

    }
}

Observing: When I left the field and put a test Alert in the js function just to see if it is working it will ... and can display the value the problem is in sending the same ajax. I enter the /test and load my view, and when I put /test/value shows nothing, an error appears:

Whoops, looks like something went wrong.
(1/1) MethodNotAllowedHttpException
  • I show the error because the method is for POST request and not for GET ai of this method message not accepted.

1 answer

1


The error appears because the route has been set only to accept the verb POST and this will work with your function in , because, face your configuration is for the verb POST same as configured on your route.

If you want this method to work with others as well verbos configure the path file as follows:

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

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

and also has the way to release all the verbos:

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

Note: the correct is to have a route and a verbo configured for each address, ie only create another route configuration and that is configured for that controller and método, but, in the there is the option to configure as mentioned just above.


On the part of 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>

References

  • I understood why it doesn’t work when I put the direct post method in the browser ... But I must be doing something wrong in relation to sending Ajax because my request does not reach my Controller

  • @I made an edition.

  • I’m here trying and it hasn’t worked yet, but with your help with the ajax method now it returns me error. I left the following route Route::post('/teste/valor', 'TesteAjaxController@valor'); and changed the ajax url to url:'/test/value'. This should work?

  • To make it easy to create a var with the name of truck = 'http://localhost/Projects/Projectjax/public/test/value' and I make the url receive this value and still gives error

  • What’s the mistake? @Brunoasimiodasilva is surely already arriving the request

  • 1

    The error was the name of my token that was under the wrong name! Thanks for the help !

Show 1 more comment

Browser other questions tagged

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