Skip to content
Advertisement

API: Ajax post in Laravel – 403 (Forbidden)

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

web.php

JavaScript

index.blade.php

JavaScript

app.js

JavaScript

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

Note : use either ajax headers for csrf or in data like this:

JavaScript

FOR MORE : https://laravel.com/docs/8.x/csrf

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement