You cannot redirect using the POST
method as it is a shortcut to Response::redirect()
which is defined as
This method adds a "Location" header to the current response.
What you can do alternatively to achieve the desired effect is to call the actionDelete
via ajax and response a success
or failure
from the action to the ajax call where you can submit the id
using the $.post()
.
For example consider the following code where we have a button on which we bind the click
event and get the id of the record that we need to delete, it can either be inside a hidden field, we send the request to the actionDelete
and if all is ok we submit the id using $.post()
.
$js = <<< JS
$("#delete").on('click',function(){
var id = $("#record_id").val();
$.ajax({
url:'/controller/action',
method:'post',
data:{id:id},
success:function(data){
if(data.success){
$.post('/controller/action',{id:data.id});
}else{
alert(response.message);
}
}
});
});
JS;
$this->registerJs($js,\yii\web\View::POS_READY);
echo Html::hiddenInput('record_id', 1, ['id'=>'record_id']);
echo Html::button('Delete',['id'=>'delete']);
Your actiondelete()
should look like below
public function actionDelete(){
$response = ['success'=>false];
$id = Yii::$app->request->post('id');
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
try{
$this->findModel($id)->delete();
$response['success'] = true;
$response['id'] = $id;
}catch(\Exception $e){
$response['message'] = $e->getMessage();
}
return $response;
}