Answer the question
In order to leave comments, you need to log in
Why is ajax data not being passed in Yii2?
On button click I try to remove a picture from ProductImg table by ajax request.
I send the image ID, but it does not come to the controller, in the debug console, accordingly, "Call to a member function delete() on null" is displayed. What could be wrong?
Presentation code:
<?php
echo '<div class="row row-eq-height">';
foreach($model->productImgs as $img){
echo '<div class="col-md-4" id="product-img-' . $img->id . '"><div class="product-img__container">'
.Html::img('/images/products/' . $img->alias, ['alt' => '', 'class' => 'img-responsive'])
.'<button onClick="DeleteImg('.$img->id.')" class="btn btn-danger">Удалить</button>'
.'</div></div>';
}
echo '</div>';
?>
function DeleteImg(id)
{
if (!confirm('Удалить изображение?')) {
return false;
}
$.ajax(
{
dataType: 'html',
url: '/productimg/delimage',
type: "POST",
data: {
id: id
},
success: function (data)
{
$("#product-img-" + id).hide();
},
error : function(jqXHR) {
console.log(jqXHR.responseText);
}
});
}
public function actionDelimage(){
$id = Yii::$app->request->post('id');
$model = ProductImg::findOne($id);
$model->delete();
return true;
}
Answer the question
In order to leave comments, you need to log in
Good afternoon.
Check that the id is substituted in the html
This is redundant
Check that the post has the correct value
public function actionDelimage(){
// например так
print_r(Yii::$app->reqiest->post);
$id = Yii::$app->request->post('id');
$model = ProductImg::findOne($id);
$model->delete();
return true;
}
public function actionDelimage(){
if(Yii::$app->request->isAjax){
$id = Yii::$app->request->post('id');
if(($model = ProductImg::findOne($id)) !== null){
$model->delete();
return true;
}
else{
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question