We are going to deploy the new yiiframework.com website on March 23, 2018 from 8:00 to 12:00 UTC.
Website and Yii documentation will not be available in this time frame. Check the news for more details.

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 3 comments

#18057 report it
Maciej Liżewski at 2014/09/02 10:57am
There is security issue with proposed solution

CSRF must be provided only for POST requests. If you also add CSRF token to GET requests it can be exposed and/or logged in log files which may be a security hole. CSRF token must be kept private...

#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