Reputation: 41
I'm new to Laravel. I'm attempting a simple Ajax request however I get the following error message. What does this mean?
{message: "", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…} exception: "Symfony\Component\HttpKernel\Exception\HttpException" file: "C:\MAMP\htdocs\project_21_my_laravel_website\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php" line: 204 message: ""
index.blade.php
<div class="myTestLink">my Test Link</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".myTestLink").click(function(){
$.ajax({
method: 'post',
dataType: 'json',
url: 'insert-ajax',
success: function (data)
{
alert(data);
}
});
});
});
</script>
web.php
Route::post('/insert-ajax', 'myTestController@testingsomething');
myTestController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class myTestController extends Controller
{
public function testingsomething()
{
return "hello";
}
}
Upvotes: 2
Views: 2858
Reputation: 3751
You must use CSRF
token.
Please add the meta tag within the head tag in the blade file.
<meta name="csrf-token" content="{{ csrf_token() }}">
Then change your javascript like this.
$(document).ready(function () {
$(".myTestLink").click(function(){
$.ajax({
method: 'post',
dataType: 'json',
url: 'insert-ajax',
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data)
{
console.log(data)
}
});
});
}
Upvotes: 4
Reputation: 431
Please add the meta tag within the head tag in the blade file.
<meta name="csrf-token" content="{{ csrf_token() }}">
Then in the scripts section please add the following:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
For reference you can go through this the documentation doc. Hope this helps and solves the issue. Thanks.
Upvotes: 1