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

0 3
Viewed: 27 306 times
Version: 1.1
Category: Tutorials
Written by: jasonban
Last updated by: CeBe
Created on: Jan 20, 2014
Last updated: 10 years ago
Update Article


View all history

Related Articles