Roby Sottini
Roby Sottini

Reputation: 2265

Yii2: How to redirect with POST method?

I have the Yii2 delete action in a controller and I need to redirect to index.php with the id variable by POST method. This is how I do it with GET method:

public function actionDelete($id)
{
    $this->findModel($id)->delete();

    return $this->redirect(['index?id=' . $id]);
}

How can I redirect using the POST method?

Upvotes: 5

Views: 6686

Answers (2)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23778

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

Upvotes: 4

Andrei Lupuleasa
Andrei Lupuleasa

Reputation: 2762

I don't think it is possible, see below link:

https://forum.yiiframework.com/t/redirect-with-post/36684/2

Upvotes: 1

Related Questions