Yii 1.1: default csrf security and ajax post in one controller


Hello Yii friends

I am going to write an article. Many times we write same code on every ajax call, but writing a single code in one controller is sufficient in ajax post with csrf security which is very easy.

At first go to components and open the controller.php

Simply add the following code:

// this function will be initialize in every controller call which will call initAjaxCsrfToken function
    public function init() {
    // this function will work to post csrf token.
    protected function initAjaxCsrfToken() {
        Yii::app()->clientScript->registerScript('AjaxCsrfToken', ' $.ajaxSetup({
                         data: {"' . Yii::app()->request->csrfTokenName . '": "' . Yii::app()->request->csrfToken . '"},
                    });', CClientScript::POS_HEAD);

Enjoy coding

Total 2 comments

#17145 report it
Stageline at 2014/05/07 07:57am

This is an global ajax option but not required.

Yii automatically insert csrf token into forms wheen csrf validation is enabled.

<form id="formID"......><input type="hidden" name="csrfToken" value="...."></form>
    url: 'xyz',
    data: $('#formID').serialize(), /*this store required csrf token because is in form hidden field. */
#16765 report it
Rajith R at 2014/03/26 02:22am

I didn't get the exact usage of this wiki article . Please explain!

Leave a comment

Please to leave your comment.

Write new article