mgarneau
(Maxime Garneau)
October 19, 2010, 4:13pm
1
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
Jay_69
(Biz)
January 28, 2011, 10:24pm
2
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:
$('#container_id').load('?r=controller/action',{var1:value,var2:value,YII_CSRF_TOKEN:document.getElementsByName('YII_CSRF_TOKEN')[0].value});
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.
gusnips
(Gustavo)
January 28, 2011, 10:34pm
3
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
Jay_69
(Biz)
January 28, 2011, 10:56pm
4
Please pay attention to the date of the post, its 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.
macinville
(Macinville)
January 29, 2011, 5:36am
5
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!
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?
Say_Ten
(Yii)
June 7, 2011, 3:40pm
7
That sounds more like you’ve got parameters in your action and they don’t line up with the url and routing.
Jesse
(Jmcowell)
March 25, 2013, 6:00pm
8
Jay_69:
Hi !
May be this one could help. I use this trick by myself in my JS:
$('#container_id').load('?r=controller/action',{var1:value,var2:value,YII_CSRF_TOKEN:document.getElementsByName('YII_CSRF_TOKEN')[0].value});
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.
Thank you Jay. Your "trick" worked for me.