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.
– novic