In the HTML page request Ajax times 400 error, solve Yii submit post form 400 error, and Ajax post request 400 problem (example code)

Post form 400 error:

Right way:

Add this in the head section of your layout:

= Html::csrfMetaTags() ?& gt;

———————————

It is not recommended to cancel CSRF token verification as follows:

Add this in your controller:

public $enableCsrfValidation = false;

Other methods:

The original problem is CSRF verification, because the form is written by itself. In the framework of Yii, in order to prevent CSRF attacks, CSRF token verification is encapsulated in the form data of post.

Solution turn off CSRF verification

Method 1: close in the funding document

‘components‘=> array(

‘request‘=> array(

// Enable Yii Validate CSRF Token

‘enableCsrfValidation‘ => true,

),

),

When using the Yii form to generate a page, if the form is submitted by post, a hidden field will be added to the page, which is the CSRF token verification field

When users submit the form, they submit the field to the server. The Yii framework will send the hidden field submitted by the client and the Yii in the cookie submitted by the client_ CSRF_ The value of token was compared.

If it is the same, it will continue to execute. If it is not the same, it will throw a 400 exception: “the CSRF token could not be verified.”.

So the above problem appears. If you write your own form, you can add a hidden token verification field to the form on the view page

Method 2: add hidden verification fields in the form

If you don’t want CSRF verification, modify the true of method 1 to false, so that Yii won’t do post form verification.

Ajax post 400 error:

Ajax post is also used in movies recently. So I’m looking for answers on the Internet. Finally, I found the answer in Yii from unintentionally_ CSRF_ Token, because I have enabled enable csrfvalidation ‘= & gt; true  , So CSRF verification is added to the request. So when Ajax makes an Ajax post request, it can’t pass the verification.

Solution: just add Yii manually when you request_ CSRF_ Just token!

For example:

//Send Ajax $. Ajax ({type: “post”, datatype: “JSON”, URL: “index. PHP?R = movie/insertfavorite”, data: {movie_ id‘:‘<?php echo $_ GET[‘id‘]?& gt;‘,‘ YII_ CSRF_ TOKEN‘:‘<?php echo ii::app()-> request-> csrfToken>‘}, cache: false, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); }, success:function(data){ var result=eval(“(“+data+”)”); alert(data) }, });

Read More: