CodeIgniter Forums
*Tip:CSRF + Ajax - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: *Tip:CSRF + Ajax (/showthread.php?tid=63927)



*Tip:CSRF + Ajax - BrendanRehman - 12-23-2015

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