Codeigniter 4 with Ajax CSRF ISSUE - The action you requested is not allowed
Asked Answered
B

1

0

If you have ever come accross this error using codeigniter 4 with Ajax. The action you requested is not allowed. as a result of csrf protection.

CRITICAL - 2023-06-10 03:41:17 --> The action you requested is not allowed.
in SYSTEMPATH/Security/Security.php on line 306.
 1 SYSTEMPATH/Security/Security.php(306): CodeIgniter\Security\Exceptions\SecurityException::forDisallowedAction()
 2 SYSTEMPATH/Filters/CSRF.php(55): CodeIgniter\Security\Security->verify(Object(CodeIgniter\HTTP\IncomingRequest))
 3 SYSTEMPATH/Filters/Filters.php(173): CodeIgniter\Filters\CSRF->before(Object(CodeIgniter\HTTP\IncomingRequest), null)
 4 SYSTEMPATH/CodeIgniter.php(473): CodeIgniter\Filters\Filters->run('api/v1/notification/markasseen/4', 'before')
 5 SYSTEMPATH/CodeIgniter.php(368): CodeIgniter\CodeIgniter->handleRequest(null, Object(Config\Cache), false)
 6 FCPATH/index.php(68): CodeIgniter\CodeIgniter->run()

Check the solution below. I was faced with the same issue, so i decided to help people out there who might facing the same issue

Bicuspid answered 10/6, 2023 at 3:50 Comment(1)
B
0

ULTIMATE SOLUTION

Add this code in your ajax

data : JSON.stringify({'<?= csrf_token() ?>':'<?= csrf_hash() ?>'}),

    $.ajax({
    url: baseUrl + "/api/v1/notification/markasread/" + id,
    data : JSON.stringify({'<?= csrf_token() ?>':'<?= csrf_hash() ?>'}),
    type: "POST",
    dataType: "json"
    }).done((data)=>{
        console.log(data);
    }).fail((jqXHR, ajaxOptions, thrownError)=>{
        console.log("Error " + thrownError);
Bicuspid answered 10/6, 2023 at 3:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.