0
votes

I am trying to make an example of Ajax request with Laravel 5.4.

The test example is simple, just enter a numeric value in an input = text field in my View and leave the field to send to the Controller, then add + 10 to that value and then return that value to my View so that it can displayed on 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 split it to make it easier to interpret.

<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){
                    alert('Success');
                },
                error:function(){
                  alert('Error');
                },
            });


       });
    });
</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 valor(Request $request)
    {
        $valor= $request->input('valor');
        $valor += 10;
        return $valor; // How do I return in json? in case of an error message?

    }
}

Always when I try to send the request via ajax it goes to alert ('Error'). is it that I'm doing something wrong in sending the ajax or route?

1
error:function(e){ console.log(e); }, Here you can find what kind of error you are facing - Muthu17
There is no valor method in your controller, which you are accessing via 'TesteAjaxController@valor' - linktoahref
Please add valor() function in your controller. - Muthu17
There is no meta tag in your example. Try to add <meta name="csrf-token" content="{{ csrf_token() }}"> to head. - Andriy Lozynskiy
Check the Laravel error log there detail description of error would be present check what it says, chances are there is an error in server side script. your client side scripts looks okay. - Arpita

1 Answers

4
votes

to return a json response. you need to use.

response()->json([
 'somemessage' => 'message',
 'valor' => $valor
]);

UPDATE: you are getting an error alert because i think your route method doesnt match your controller methods.

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

where in your controller you have

public function cep() ...