Yii2 ajax bad request (#400)

  $.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#добавление_csrftoken_в_ajax_запрос_yii2


This is my code now, 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>');
                }
            }
        });
    });

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>

You can try this way. It's work!

var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
         url: 'request',
         type: 'post',
         dataType: 'json',
         data: {param1: param1, _csrf : csrfToken},
});