Codeigniter 2 Ajax Problems

Whilst building a new site for a client I was building an AJAX call to re-order images on the fly as to speak.

I use jquery and Ajax all the time. But this time I was getting nothing but 500 error.

OK I'd just upgraded to using Codeigniter 2, jQuery 1.5 and jQuery 1.8.9. I'm not seeing any javascript errors in Firebug.

Several hours later and a sore head from all the bang on the desk I found the reason and solution.

Codeigniter 2 has quite rightly improved it's security with a new security class which includes a function for Cross Site Scripting. This function automatically creates a hidden token inside your form which is used to validate the form as having come from your server on submit.  This is great and you switch it on from inside the config file and why wouldn't you!

When you submit a form or content through AJAX your controller receives the data that you have specified in your Ajax post function and does what ever you've set it up to do.

Here comes the rub......

The codeigniter security class will now stop the data from being passed to your controller because you're missing the hidden token from inside your form.

Solution is simple

create a variable inside your jquery function that retrieves the hidden field value.

var crsx = $("input[name=csrf_test_name]").val(); // crsf_test_name is the default name in the config file - I would recommend changing it.

Then add that to your data as crsf_test_name:crsx

I found a good walk through of this

http://aymsystems.com/ajax-csrf-protection-codeigniter-20

He also goes through using post for non-form data.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.