Answer the question
In order to leave comments, you need to log in
How to make an Ajax request correctly?
Hello, I'm new to Yii, I created a DatePicker, but when I update its values, it doesn't update in the database. I tried to make an ajax request, but apparently I don’t understand something.
[
'label' => 'Дата начала подписки',
'value' => function ($model, $key, $value) {
return \kartik\date\DatePicker::widget([
'name' => 'date_subscription',
'model' => $model,
'value' => $model->date_subscription,
'type' => DatePicker::TYPE_INPUT,
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'autoclose' => true,
],
]);
},
'format' => 'raw',
],
$(".krajee-datepicker.form-control").blur(function() {
jQuery.ajax({
url: '/admin/clients/date-subscription',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
async: true,
dataType: 'html',
data: {
data: this.value
},
success: function (data) {
alert(data);
},
error: function () {
alert("Error");
location.reload();
}
});
});
Answer the question
In order to leave comments, you need to log in
In general, the situation is this ...
I don’t know how to fasten an ajax request in the widget itself.
But you can do this:
add 'contentOptions' to the GridView, set the ajax request parameters and send it to the server.
[
'label' => 'Дата начала подписки',
'value' => function ($model, $key, $value) {
return \kartik\date\DatePicker::widget([
'name' => 'date_subscription',
'model' => $model,
'value' => date('d-m-Y',$model->created_at),
'type' => DatePicker::TYPE_INPUT,
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'autoclose' => true,
],
]);
},
'contentOptions' => [
'onchange' => '
var Id = $(this).parent().attr("data-key");
var uDate = $(this).children("input").val();
console.log(Id + " - " + uDate);
$.ajax({
url: "'. Url::to('user/default/ajax-request') .'",
type: "POST",
data:{id: Id, date: uDate},
success: function(data){
console.log(data)
}
})
'
],
'format' => 'raw',
],
public function actionAjaxRequest()
{
if(Yii::$app->request->isAjax){
$newDate = Yii::$app->request->post('date');
$uId = Yii::$app->request->post('id');
if(($model = Users::findOne(['id' => $uId])) != null){
$model->created_at = strtotime($newDate);
if(!$model->update(false,['created_at'])){
return 'Данные не обновились.';
}
else{
return 'Данные успешно обновились.';
}
}
else{
return 'Пользователь не найден.';
}
}
return false;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question