Yii2 ajax bad request (# 400)

When I use this code, I get this error as the answer:

Bad request (# 400): cannot verify your details

/** * Active toggle */ $(document).on('click', '[data-toggle-active-menu-items]', function(e){ e.preventDefault(); var id = $(this).data('toggle-active-menu-items'); $.ajax({ url: 'active', type: 'POST', data: {'id': id, _csrf: yii.getCsrfToken()}, contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { if (data.active == 1) { $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-open"></span>'); } else { $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-close"></span>'); } } }); }); 

I tried adding

_csrf: yii.getCsrfToken ()

and

contentType: "application / json; charset = utf-8",
dataType: "json",

but it does not work

it works when I add this to my controller, but it is not good, I do not want to disable csrf check

public $ enableCsrfValidation = false;

How can i fix this?

+6
source share
6 answers

Now this is my code, just ignore the csrf token:

 $(document).on('click', '[data-toggle-active-menu-items]', function(e){ e.preventDefault(); var id = $(this).data('toggle-active-menu-items'); $.ajax({ url: 'active', type: 'POST', data: {'id': id}, dataType: "json", success: function(data) { if (data.active == 1) { $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-open"></span>'); } else { $('#list-' + id + ' [data-toggle-active-menu-items]').html('<span class="glyphicon glyphicon-eye-close"></span>'); } } }); }); 
+2
source

You can try this. He works!

 var csrfToken = $('meta[name="csrf-token"]').attr("content"); $.ajax({ url: 'request', type: 'post', dataType: 'json', data: {param1: param1, _csrf : csrfToken}, }); 
+11
source
  $.ajax({ url: '$urlSave', type: 'post', data: {payload: payload, _csrf: yii.getCsrfToken()}, dataType: 'json', }).success(function(response) { }); 

other examples: http://docs.mirocow.com/doku.php?id=yii2:docs#adding_csrftoken_in_ajax_ request_yii2

+4
source

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> 
+2
source

In my case, I solved this problem with blocking the csrf check for the route "site / save-order" (actionSaveOrder).

 class SiteController extends Controller { ... public function beforeAction($action) { $this->enableCsrfValidation = ($action->id !== "save-order"); // <-- here return parent::beforeAction($action); } } 
0
source

I had the same problem but I noticed that I forgot to add Html::csrfMetaTags() to the section of the chapter, and this actually fixed it for me. Good luck.

0
source

Source: https://habr.com/ru/post/973149/


All Articles