Yii2 ajax bad request (#400)
24,689
Solution 1
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>');
}
}
});
});
Solution 2
$.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
Solution 3
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},
});
Solution 4
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>
Comments
-
Ruben over 3 years
When I use this code, I get this error as a response:
Bad Request (#400): Not possible to verify your data
/** * 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 that's not working
it does work when I add this to my controller, but that's no good, I don't want to disable csrf validation
public $enableCsrfValidation = false;
How can I fix this?
-
Ruben over 9 yearsI don't think it's a good solution to block csrf-verification
-
Maksim Tikhonov over 9 yearsof course, but when i try to send csrf verification key to server it doesn't recognize it, unfortunately (
-
AHMED.D over 8 yearswhat about type: 'GET' ?
-
Rostyslav Pylypenko about 8 yearsMuch more better then provided by @user3534949 stackoverflow.com/questions/25054945/…
-
Rostyslav Pylypenko about 8 yearsSorry may be my comment has "ambiguity". You got +1 for Your answer from me. My comment means that Your answer is correct! I ithink we have to delete our comments, because they are offtopic.