Monday, September 2, 2013

Yii "The CSRF token could not be verified."

Do you also get this message when use CSRF token in your Yii Application ? ok let's complete to read my posting. This is the scenario on my application when get error message :
PHP:
$form=$this->beginWidget('CActiveForm');
echo CHtml::inputField('text','txtName','') 
echo CHtml::button('Do',array('id'=>'btn','onclick'=>'proses();'))
$this->endWidget(); 
JS:
 function proses()
 {
  $.ajax({
   url: "my/proses",
   type: "POST",
   data: 'name='+ $('input["name=txtName"]').val(),
   success: function (msg) {
    alert(msg);
   }
  });
 }
when i click "Do" button, i got error 'The CSRF token could not be verified'. this is because i enable enableCsrfValidation, and Yii need to validation for all action to compare with Csrf Token. so i need to modify my code to be:
 PHP:
$form=$this->beginWidget('CActiveForm');
echo CHtml::inputField('text','txtName','') 
echo CHtml::button('Do',array('id'=>'btn','onclick'=>'proses();'))
echo CHtml::hiddenField('YII_CSRF_TOKEN',Yii::app()->request->csrfToken);
$this->endWidget(); 
JS:
 function proses()
 {
  $.ajax({
   url: "my/proses", 
type: "POST",
   data: 'name='+ $('input["name=txtName"]').val() + '&YII_CSRF_TOKEN=' + $('input["name=YII_CSRF_TOKEN"]').val(),
   success: function (msg) {
    alert(msg);
   }
  });
 }

No comments:

Post a Comment