Search code examples
codeignitercsrf-protectiongrocery-crud

GroceryCRUD add, edit buttons not working when enabling CodeIgniter CSRF protection


I am using GroceryCRUD 1.5.0 with CodeIgniter 2.2.0.

When enabling CodeIgniter's internal CSRF protection with:

$config['csrf_protection'] = TRUE;

in application/config/config.php, then the GroceryCRUD auto-generated action buttons (edit, view) and links (add) does not work anymore.

It seems that the CSRF token is not passed along in the Ajax calls (confirmed with Firebug). It is possible to use this CodeIgniter feature with GroceryCRUD?


Solution

  • I finally managed to solve my problem. Two options are available:

    The easy way:

    Set:

    $config['grocery_crud_dialog_forms'] = false;
    

    in application/config/grocery_crud.php.

    This option works well without CSRF protection enabled (that is, it can be set to true to produce more elegant forms), but fails when set if no code modifications are done in the javascript.

    The elegant way:

    If we want to use:

    $config['grocery_crud_dialog_forms'] = true;
    

    in application/config/grocery_crud.php to have the cute forms, then:

    1. include the jquery.cookie plugin in pages with forms

    2. add this code to your JS files to auto-magically insert the CSRF token in all ajax POST calls:

    $(document).ready(function() {
        var csrf_token= $.cookie('csrf_cookie_name');
    
        $.ajaxSetup({
            data: {
                'csrf_test_name' : csrf_token
            }
        });	
    });

    I hope this will help someone else.