I am new in Laravel. I try to create a ajax post function on my project. But my following code don't work. When I click the button it does not response anything but I create the function as mention on the tutorial site. I search on google but don't get any suggestion or appropriate answer. Please, anyone help me solve this problem. Any suggestion will be appreciated. My English is not good. So please, don't mind. Thank you. ohh I forget to mention that I used Laravel 5.
<html>
<head>
<title>Ajax Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
/* route file: */
Route::get('ajax',function(){
return view('message');
});
Route::post('/getmsg','AjaxController@index');
/* controller file: AjaxController.php */
class AjaxController extends Controller {
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
}
Follow this Steps:
route.php
Route::post('/getmsg','AjaxController@index');
AjaxController.php
class AjaxController extends Controller {
public function index(){
$msg = "This is a simple message.";
return response()->json([
'msg'=> $msg
], 200);
}
}
Inside View
<html>
<head>
<title>Ajax Example</title>
<meta name="_token" content="{{ csrf_token() }}" />
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
{{ Form::button('Replace Message',['onClick'=>'getMessage()']) }}
<script>
function getMessage(){
var _token = $('meta[name="_token"]').attr('content');
$.ajax({
type:'POST',
url:'/getmsg',
data: {_token: _token},
success:function(data){
$("#msg").html(data.msg);
},
error: function(data){
console.log(data);
}
});
}
</script>
</body>
</html>
Hope this help's you
For easy use, you can tell jQuery to always pass through the current csrf token. You can achieve this in two steps:
Add meta tag in your head
<meta name="csrf-token" content="{{ csrf_token() }}">
Setup your ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
After these steps, there is no need to include the token in the individual ajax requests.
Note: the docs explain this very clearly.