This is my code:
$(document).on('change', '#tblhotel-int_zone_id', function(e){
var zoneId = $(this).val();
var form_data = {
zone: zoneId
};
$.ajax({
url: "state",
type: "POST",
data: form_data,
success: function(response)
{
alert(response);
}
});
});
This shows:
Bad Request (#400): Unable to verify your data submission.
And I already have <?= Html::csrfMetaTags() ?>
. How can I fix this problem?
The most common reason for a 400 Bad Request error is because the URL was typed wrong or the link that was clicked on points to a malformed URL with a specific kind of mistake in it, like a syntax problem. This is most likely the problem if you get a 400 Bad Request error.
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).
What causes bad request errors on Chrome? Error 400 is a client error that occurs due to incorrect requests, invalid syntax, or routing issues. It can also occur if the URL is not recognized or you did not type it correctly. So, check again and make sure you typed the URL correctly.
Note: See the answer from Skullcrasher to fix the issue in the correct way as my answer suggests disabling the Cross-Site Request Forgery.
You have a problem with enableCsrfValidation. To read more about it you can read here.
To disable CSRF, add this code to your controller:
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
This will disable for all actions. You should probably, depending on the $action, disable it only for specific actions.
As the answer from Mihai P. states, your problem is CSRF validation. It is also true that you could disable the validation for your actions, but this is not considered a good solution.
As you have a problem in your Ajax request with the validation, you could also use a Yii JavaScript function to add the CSRF token to your formdata that you send in the Ajax request.
Just try to add the token to your form data as follows:
var form_data = {
zone: zoneId,
_csrf: yii.getCsrfToken()
};
I hope this helps and you therefore don't have to disable CSRF validation.
In addition to manually add the CSRF token you can check if there is an X-CSRF header set in the request.
Add this code at the bottom of your layout:
<script>
$.ajaxSetup({
data: <?= \yii\helpers\Json::encode([
\yii::$app->request->csrfParam => \yii::$app->request->csrfToken,
]) ?>
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With