I have json array in my db {"dashboard_layout":[10,9,4,5]}
I could able to sort items but not updating the sort values in the db.
$('#sortable').sortable({
helper: fixWidthHelper,
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data);
$('h6').text(data); // Checks to make sure that data is compiled correctly
$('h5').text(url); // Checks to make sure url is compiled correctly
$.ajax({
type: 'post',
data: data,
url: '" . Yii::$app->getUrlManager()->createUrl("/site/dashboard-block-sort") . "',
dataType: 'json',
success: function(data){
alert('hii');
alert(data.value);
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(thrownError);
// console.log(thrownError);
}
});
}
}).disableSelection();
In my controller
public function actionDashboardBlockSort(){
if(isset($_POST['data'])) {
$dashboardLayout = $_POST['data'];
$model = \app\models\UserPreferences::find()->where(['user_id' => Yii::$app->user->identity->user_id])->one();
// check here if model is not null
$perferencesOther = json_decode($model->others);
$perferencesOther->dashboard_layout = $dashboardLayout;
// store updated preferencves in db
$model->others = json_encode($perferencesOther);
$model->save();
echo Json::encode([
'status' => true,
'value'=>$model->others
]);
} else {
echo Json::encode([
'status' => false,
]);
}
}
is something wrong? when I alert(data)
in view page.I am getting correct sort value like item[]=10&item[]=9&item[]=5&item[]=4
but not able to post to the controller.
Shouldnt you be using $_POST['item']
rather than $_POST['data']
in your action as you are posting serialize string with array item[]
inside data
which is a javascript var
.
public function actionDashboardBlockSort(){
if(isset($_POST['item'])) {
$dashboardLayout = $_POST['item'];
$model = \app\models\UserPreferences::find()->where(['user_id' => Yii::$app->user->identity->user_id])->one();
// check here if model is not null
$perferencesOther = json_decode($model->others);
$perferencesOther->dashboard_layout = $dashboardLayout;
// store updated preferencves in db
$model->others = json_encode($perferencesOther);
$model->save();
echo Json::encode([
'status' => true,
'value'=>$model->others
]);
} else {
echo Json::encode([
'status' => false,
]);
}
}