cakephp helper ajax,CakePHP ajax post keeps returning 400 Bad Request

Protection against form tampering is one of the basic features provided by the Security Component. As long as it is enabled, it is going to treat all POSTs as form submissions.

A regular hand-coded HTML form won't work with the Security Component enabled, so neither will a JQuery-generated POST. You can, of course, use $this->Security->validatePost = false; or $this->Security->csrfCheck = false; but then you loose the protection that the Security Component provides.

To keep the Security Component on and working as normal, you need to use the CakePHP Form Helper to create the form you're going to post via ajax. This way the data[_Token][fields] and data[_Token][unlocked] hidden fields get generated with their keys:

echo $this->Form->create('Test',array('id'=>'testform'));

echo $this->Form->input('Something');

echo $this->Form->submit();

echo $this->Form->end();

?>

This will generate something like this:

Now it's just a matter of serializing this form in JQuery so that it can be sent with the ajax POST:

$('#testform').submit(function(event) {

$.ajax({

type: 'POST',

url: "/your/url",

data: $('#testform').serialize(),

success: function(data){

alert('Wow this actually worked');

},

error:function() {

alert('This will never work');

}

});

event.preventDefault(); // Stops form being submitted in traditional way

});

Now if you press the submit button, the POST will succeed.

IMPORTANT: Due to the fact that the Form Helper's Tokens can only be used with the Security Component once, this solution only works if you only intend to POST once per page generation. If you need to be able to post the same form several times between page reloads then you'll need to do the following when you add the Security Component at the beginning of your Controller:

public $components = array(

'Security' => array(

'csrfUseOnce' => false

)

);

...this will allow the tokens to be used for more than one request. It's not as secure but you can combine it with csrfExpires so that the tokens will expire eventually. This is all documented in the CSRF configuration section of the Cake book.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值