I am trying to get an Ajax response using Laravel 5 but it just wont work. This is the error I see in the Chrome debugger:
POST http://localhost:8000/getmsg 500 (Internal Server Error)send @ jquery.min.js:4ajax @ jquery.min.js:4getMessage @ ajax:10onclick @ ajax:25
This is message.php in resources/views:
<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>
This is my Ajaxcontroller.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AjaxController extends Controller {
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
}
Then I added this to the web.php in routes:
Route::get('ajax',function(){
return view('message');
});
Route::post('/getmsg','AjaxController@index');
Change the url in this ajax code to the correct path (e.g //public/getmsg)
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/<project_name/public/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
You can set CSRF token once for all your calls:
<script>
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
</script>
And you can return array in your action and it will be automaticly converted to json:
public function index(){
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
change in ajax call if your url in htttp://hostname/getmsg
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'<?php echo url('/') ?>/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
I did it by setting the ajax type to GET:
<script>
function getMessage(){
$.ajax({
type:'GET',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
And the route set to get instead of post:
Route::get('/getmsg','AjaxController@index');
This works but I have absolutely no idea why the POST method doesn't at all. I think the appropiate solution for this would be to know why POST doesn't work so please, even though this one works too, if someone knows how to do it with POST just tell.