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:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use DB;

class API extends Controller
{
    public function getSomething(Request $r)
    {
        $r->validate([
            'user' => 'required'
        ]);

        $data = DB::table('posts')->orderBy('id', 'desc')->get();



        return $data;
    }
}

web.php

Route::group(['prefix' => 'api'], function(){
    Route::post('getSomething', 'API@getSomething');
});

index.blade.php

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />

.... some of my content ....

<script src="{{ asset('assets/js/app.js') }}"></script>

app.js

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    url: '{{ url("api/getSomething") }}', 
    type: 'POST',
    data: {
        user: '1',
        _token: '{{ csrf_token() }}',
        _testThisAjax: true
    },
    success: function (c) {
        console.log(c);                                         
    },
    error: function(e)
    {
        console.log(e);
    }

});

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

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    url: '/api/getSomething', 
    type: "POST",
    data: {
             user: '1',
             _testThisAjax: true
    },
    success: function (c) {
        console.log(c);                                         
    },
    error: function(e)
    {
       console.log(e);
    }
});

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

 data: {_token: $('meta[name="csrf-token"]').attr('content') , 'key' : 'value'}

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

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