If you use CodeIgniter (CI) like me, you’ve probably read/heard about the CSRF protection that comes built into this great framework.  I typically kept ajax functionality (form submissions in this case) to a minimum as I wanted to focus more on development and finishing a project than prettying it up with ‘Web 2.0’ stuff.

Well in a couple of my last projects I’ve ran smack into CSRF protection and how it impacts AJAX (as well as many other things like Paypal payment gateway responses, etc).

If you found this page when searching for Codeigniter CSRF Ajax, then you’re in luck, as here is the easiest way to add CSRF protection to your ajax calls:

$.ajax({
	type: 'POST',
	url: '/action/fetch_more_blog_posts',
	data: {
		type: 'news', limit: limit, offset: offset,
		<?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>' },
	success: function(data) {
		$(data).appendTo('#more-entries');
		$('#older-posts').slideDown();
		offset += limit;
	}
});

The magic really here is the following entry in the data I am sending back to my controller:

<?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'

The `get_csrf_token_name()` gets you your token name from the security class (first set in your config), and the `get_csrf_hash();` simply outputs the secure hash from the security class. Simple enough.

If you have timeout issues (say your ajax page sits too long, you may increase the token a bit, test for best fit).



4 Comments to “Enabling CSRF Protection in CodeIgniter for AJAX calls”

  1. Jason Adriaan | April 27th, 2012 at 8:20 PM

    Awesome! It simply works. Love it.

  2. Jed Lagunday | January 16th, 2013 at 3:45 AM

    Thanks

  3. David | April 26th, 2013 at 2:49 PM

    I’m on a tight deadline here, and struggling with this for ages now.
    Any suggestions on how to go about this when embedding a .js file, rather than having it sit in the php file?

  4. Atul patel | June 11th, 2015 at 5:03 AM

    You Just amazing !!

Leave a Comment