E
E
Evgenya-k22019-05-29 14:16:49
Yii
Evgenya-k2, 2019-05-29 14:16:49

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>';
?>

JS:
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);
            }
        });
}

Controller code (the images themselves are deleted in the model in the beforeDelete() method):
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

1 answer(s)
D
Dmitry, 2019-05-29
@Evgenya-k2

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;
    }

Perhaps the required model is not returned in findOne
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 question

Ask a Question

731 491 924 answers to any question