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