gilvandev gilvandev - 8 months ago 47
PHP Question

Ajax call crash on CodeIgniter - CSRF Error 403

I'm trying to perform Ajax calls within CodeIgniter. As had already searched before, when the CSRF protection is active, a hash (randomly generated) must be submitted with each request to the server.

In research I found the following code to always hash to be sent along with the other data through the Ajax request:

data: {
arquivo_facil_tk: $.cookie('arquivo_facil_co')

So I got a positive result on the first call right after the page is loaded. But to attempt a second call, get the error 403. I also found the option of adding this code snippet for each Ajax call I make, but as my software performs several calls, it becomes unfeasible and rude.

How could I fix this? Also tried using the beforeSend event but got the same error.


Rather than using ajaxSetup simply include the CSRF token along with the data in your actual AJAX call like so:

data: {var: value, arquivo_facil_tk: $.cookie('arquivo_facil_co')}

or if you're serializing forms simply:

data: $(this).serialize() + '&arquivo_facil_tk=' + $.cookie('arquivo_facil_co')