Manually Add Csrf Token To Ajax Calls


I have this form that I need to send to controller using ajax but I can’t use form widget because I don’t have a model for it!

now I also have enabled the CSRF token validation but my ajax call doesn’t have it.

so I was looking for a way to add this token to the ajax POST data.

in other words how can I make an ajax call with CSRF token in it?

tank you.

Hi mohsen.shakiba,

Why don’t you make a CFormModel for it?

You can use CHttpRequest::csrfToken and CHttpRequest::csrfTokenName.


$csrfTokenName = Yii::app()->request->csrfTokenName;

$csrfToken = Yii::app()->request->csrfToken;


Yii::app()->clientScript->registerScript("something", "



  type: "POST",

  url: "somewhere",

  data: { name: "John", location: "Boston", $csrfTokenName: "$csrfToken"},



tank you a lot, you really saved me a lot of time

now there’s another tiny question

if I send this data

data: { name: "John", location: "Boston", $csrfTokenName: "$csrfToken"},

the way you have described here, by the POST request

what name I should expect in my controller?

cause I’m supposed to get the data like this

$POST[the name]

and what might that name be?


But you don’t have to worry about the csrf token’s name, just as you didn’t when you were handling non-ajax posts before. Yii will take care of it.

Tnax again and a lot ;)