Mohan Prasad Mohan Prasad - 2 months ago 34
Ajax Question

Own Ajax Request to delete action in yii2 not working

In my Yii2 I am trying to write my own ajax request to perform delete action.

My code for the action column button
**

'delete' => function ($url, $model) {
return '<span class="glyphicon glyphicon-trash delete-prod" id="'.$model->product_id.'" style="cursor:pointer;"></span>';**
},


My Ajax request for this :

<?php
if($model!= null){
foreach($model as $mod);
}
$this->registerJs('
jQuery("body").on("click", ".delete-prod", function() {
var id = $(this).attr("id").split("-")[1];
alert(id);
$.ajax({
type: "POST",
cache: false,
data:{"refID": id},
url: "'.Yii::$app->getUrlManager()->createUrl("product/delete?id=".$mod->product_id).'",
dataType: "json",
success: function(data){
if(data.status){
alert("hello");

}else{
alert(data.message);
}
}
});
});
');
?>


My Delete action in the controller

public function actionDelete($id)
{

\app\models\Productlines::find()->where(['product_id' => $id])->one()->delete();

return $this->redirect(['index']);
}


For some reason I just get the alert when i click the button. My delete action doesn't work. I get a 500 Internal Server Error. Can any one help me out with this??

Thanks a million...

Answer

Try this

$url=Yii::$app->getUrlManager()->createUrl("product/delete");
$this->registerJs('
  jQuery("body").on("click", ".delete-prod", function() {
    var id = $(this).attr("id");   
    alert(id);//check whether you are getting the correct id value     
    $.ajax({
        type: "POST",
        cache: false,
        data:{"refID": id},
        url: "'.$url.'",
        dataType: "json",
        success: function(data){ 
           alert(data.status);
        }
    });
});
');

Your Controller code

public function actionDelete()       
{
    Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
    $p = Yii::$app->request->post();
    $id=$p["refID"];


    if(\app\models\Productlines::find()->where(['product_id' => $id])->one()->delete())
     {
         return [
            "status" => "success"
        ];
     }
     else
     {
          return [
            "status" => "failure"
        ];
     }


}