I’m getting 403 forbidden
during ajax call.
This is happen only if the ajax
is on app.js
.
If I remove
from app.js
and put to index.blade.php
, is working perfectly.
How can I make it working also on my app.js
?
I’ve searched a lot, and found I needed to add this
$.ajaxSetup({ headers: { ‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’) } });
before the ajax, but is still not working..
controller:
JavaScript
x
23
23
1
<?php
2
3
namespace AppHttpControllers;
4
5
use IlluminateHttpRequest;
6
use DB;
7
8
class API extends Controller
9
{
10
public function getSomething(Request $r)
11
{
12
$r->validate([
13
'user' => 'required'
14
]);
15
16
$data = DB::table('posts')->orderBy('id', 'desc')->get();
17
18
19
20
return $data;
21
}
22
}
23
web.php
JavaScript
1
4
1
Route::group(['prefix' => 'api'], function(){
2
Route::post('getSomething', 'API@getSomething');
3
});
4
index.blade.php
JavaScript
1
7
1
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
2
<meta name="csrf-token" content="{{ csrf_token() }}" />
3
4
some of my content . .
5
6
<script src="{{ asset('assets/js/app.js') }}"></script>
7
app.js
JavaScript
1
24
24
1
$.ajaxSetup({
2
headers: {
3
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
4
}
5
});
6
7
$.ajax({
8
url: '{{ url("api/getSomething") }}',
9
type: 'POST',
10
data: {
11
user: '1',
12
_token: '{{ csrf_token() }}',
13
_testThisAjax: true
14
},
15
success: function (c) {
16
console.log(c);
17
},
18
error: function(e)
19
{
20
console.log(e);
21
}
22
23
});
24
Advertisement
Answer
Since {{ url() }}
helper method will not work in app.js
file so you have to set url
in ajax
Your ajax should be like this if you put this in app.js
JavaScript
1
19
19
1
$.ajax({
2
headers: {
3
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
4
},
5
url: '/api/getSomething',
6
type: "POST",
7
data: {
8
user: '1',
9
_testThisAjax: true
10
},
11
success: function (c) {
12
console.log(c);
13
},
14
error: function(e)
15
{
16
console.log(e);
17
}
18
});
19
Note : use either ajax headers for csrf or in data like this:
JavaScript
1
2
1
data: {_token: $('meta[name="csrf-token"]').attr('content') , 'key' : 'value'}
2
FOR MORE : https://laravel.com/docs/8.x/csrf