CodeIgniter Forums

Full Version: *Tip:CSRF + Ajax
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Guys,

This is a quick post on how to setup CSRF protection and Ajax in your CI app. When you set the
PHP Code:
$config['csrf_protection'] = TRUE
to TRUE every form you POST to a controller method has an auto generated CSRF token.

So here's the fix for when you want this to work with all your Ajax calls.

1. Add following code inside your html head tag in your master template or where ever you will be using ajax.

PHP Code:
<?php
        $csrf 
= array(
 
           'name' => $this->security->get_csrf_token_name(),
 
           'hash' => $this->security->get_csrf_hash());
 
       ?>

<input id="app_csrf" type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" /> 

2. Setup your ajax, this happens before any ajax requests are made.

Code:
<script>
   $.ajaxSetup({
       data: {
           csrf_test_name: $("input[id='app_csrf']").val()
       }
   });
</script>

Voila! You're done, all your ajax requests are CSRF protected.

Enjoy,
Brendan