HTTP bad request (#400) in Yii2 ajax calls

Are you facing problems with a HTTP 400 bad request for AJAX and POST requests in Yii Framework 2.0? Some examples reported by users as of June 2014, are in extensions that use AJAX processing:

HTTP Bad Request Issue Examples

Why are you facing this error?

A common reason, (especially if you have an Yii 2 install before June 2014), is that CSRF validation is enabled in your default application setup. As of June 2014, there has been some major changes to the Yii 2 core framework with regards to automatic CSRF meta tag generation. This feature has been removed from View class for Yii 2. This is the related commit #6b799d3 and the related issue #3558.

Solution

To resolve the issue, ensure you have embedded the following code to your view layout files head section. The view layout file (e.g. main.php) is typically located in your application views/layouts directory.

// main.php
<head>
// other meta tags
<?= Html::csrfMetaTags() ?>
</head>

One thought on “HTTP bad request (#400) in Yii2 ajax calls

  1. Hello Kartik,

    Can you help me with this 400 error?
    I am trying to get work your DetailView with DateControl but with no success.

    Ajax call for datecontroll/parse/convert fails with 400 error. It happens only when csrf token is enabled. If I disable it, ajax call works perfect.

    I have included Html::csrfMetaTags() in head section of my page but this does not solve my problem.

    I have read that this token should be enclosed in ajax call but your code does not send it.
    What can I do to make it work?

    PS. Thank you for your awesome job.

Comments are closed.