400 Bad Request after sending AJAX post request in

2019-07-09 02:37发布

I want to post data via ajax to some specific controller like this :

<script>
    var myUrl = "<?php echo Url::to(['table/edit']); ?>";
</script>
$.ajax({
            type : "POST",
            url : myUrl,
            data: {id: userID},
            success  : function(response) {
                alert("Table is editted");
            }
        });

And in the controller I want to get this posted data and do some thing else. But when I try this I am getting an error "400 (Bad Request)". If someone can help it would be great! Thanks!

标签: php ajax yii2
2条回答
Juvenile、少年°
2楼-- · 2019-07-09 03:34

Just add csrf like :

       <script>
         var myUrl = "<?php echo Url::to(['table/edit']); ?>";        
       </script>
       $.ajax({
            type : "POST",
            url : myUrl,
            data: {id: userID,_csrf:'<?=\Yii::$app->request->csrfToken?>'},
            success  : function(response) {
                alert("Table is editted");
            }
        });
查看更多
Summer. ? 凉城
3楼-- · 2019-07-09 03:42

yii\web\BadRequestException (represents HTTP error with code 400) can be thrown in following cases:

1) Unable to verify your data submission. CSRF validation is enabled and failed. I don't think it's the reason in your case, because it's enabled by default and included in meta tags. When using jQuery, you don't have to send it manually.

2) Missing required parameters.

If you have parameters without default values, for example:

public function actionTest($someParam)
{
    ...
}

If you didn't pass someParam, exception will be thrown.

3) Invalid JSON data in request body.

If you send JSON as parameter and it's not a valid JSON.

4) Invalid data received for parameter. Thrown during binding parameters to action:

if ($param->isArray()) {
    $args[] = $actionParams[$name] = (array) $params[$name];
} elseif (!is_array($params[$name])) {
    $args[] = $actionParams[$name] = $params[$name];
} else {
    throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
        'param' => $name,
    ]));
}

Last two are rarely meet, especially the last one (can't remember even single time when I met it).

These should be all possible cases at the moment, I did global search through sources just to make sure.

查看更多
登录 后发表回答