Here I have a presentation with the button to delete the attached image

<?= $form->field($model, 'imageFile')->fileInput() ?> <?php if ($model->image) { echo "<div class='form-group'><div class='fimg-box'>"; echo '<img width="100" src="'.Yii::$app->params['domainFrontend'].'/images/'.$model->image.'" />'; echo Html::a('<span class="glyphicon glyphicon-trash"></span>', ['course/deleteimage', 'id' => $model->id], ['class' => 'link-del']); echo "</div></div>"; } ?> 

And the action itself:

  public function actionDeleteimage($id) { $model = $this->findModel($id); $imgName = $model->image; unlink(Yii::getAlias('@upload/images/').$imgName); $model->image = null; $model->update(); return $this->redirect(['update', 'id' => $model->id]); } 

How to make this removal through Ajax or through the weep?

    1 answer 1

    In view:

     echo Html::a('<span class="glyphicon glyphicon-trash"></span>', ['course/deleteimage', 'id' => $model->id], [ 'onclick'=> "$.ajax({ type:'POST', cache: false, url: '".Url::to(['course/deleteimage', 'id' => $model->id])."', success : function(response) { $('.link-del').html(response); } }); return false;", 'class' => 'link-del' ]); 

    In controller:

     public function actionDeleteimage($id) { $model = $this->findModel($id); $imgName = $model->image; unlink(Yii::getAlias('@upload/images/').$imgName); $model->image = null; $model->update(); if (Yii::$app->request->isAjax) { return 'Deleted'; } else { return $this->redirect(['update', 'id' => $model->id]); } }