I use AJAX calls to update my database when a user votes on an article. I submit the data to the controller through a POST. Now I would like to enable CSRF prevention. How can I make my AJAX calls work with CSRF enabled?

Note: I am not using CHtml::ajaxLink

Hi !

May be this one could help. I use this trick by myself in my JS:


This is use of jQuery load() function. As you can see we could pass any vars including YII_CSRF_TOKEN to the action.

So you can use it on any JS events.

The post is 3 months old

anyway, you are right, but ajaxLink uses yii ajaxOption ‘update’ or ‘replace’ , which doesnt do what you said

using normal JS your way is the right way

Dear Gustavo!

Believe or not the date is not important as long as the other users could search and found the HOT topic.

Hope this will be helpful to the others. :)

Date might not be important, but the version is important. The user might be using the 1.1.4, now we have 1.1.6. But since the problem is JS related, it might be the version of jquery that matters, or maybe nothing at all. But still,something to keep in mind. :)

But hey, it’s the intention that counts! Keep it up Jay! B)

I tried this solution (and something similar) and no longer get the CSRF error, but now get this different error:

Your request is invalid.

Does this imply that the CSRF token I generated is… invalid?

That sounds more like you’ve got parameters in your action and they don’t line up with the url and routing.

Thank you Jay. Your "trick" worked for me.