ci ajax js,javascript - Codeigniter ajax CSRF problem - Stack Overflow

The only problem with a few of the above answers is that a csrf token is only valid for one request, so if you make a post request via ajax and do not refresh the page you will not have the current csrf token for your next ajax post request. This is my solution:

In your CodeIgniter Controller:

$data = array('data'=> 'data to send back to browser');

$csrf = $this->security->get_csrf_hash();

$this->output

->set_content_type('application/json')

->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));

$data = the data to return to the browser

$csrf = new csrf token to be used by the browser for next ajax post request

Obviously you can output this in other ways but JSON is used mostly with ajax calls. Also include this token in every post response to be used for the next post request

Then in your next ajax request (javascript):

var token = data.csrf;

$.ajax({

url: '/next/ajax/request/url',

type: 'POST',

data: { new_data: 'new data to send via post', csrf_token:token },

cache: false,

success: function(data, textStatus, jqXHR) {

// Get new csrf token for next ajax post

var new_csrf_token = data.csrf

//Do something with data returned from post request

},

error: function(jqXHR, textStatus, errorThrown) {

// Handle errors here

console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );

}

});

Also remember that where I've got csrf_token:token replace crf_token with the name of your token found in application/config/config.php on line that states $config['csrf_token_name'] = 'csrf_token';