Search code examples
javascriptphpjqueryajaxyii2

yii2 error in ajax request in controller redirect function


I have this request in js

requestSend: function(e)
{
    let data = {
        request_id: e.target.dataset.request_id
    };
    $.ajax(
    {
        url: '/posts/save-changes',
        method: 'post',
        dataType: 'html',
        data: data,
        success: function()
        {
            console.log('success');
        },
        error: function()
        {
            console.log('error');
        }
    });
},

In php controller everything looks like this

public function actionSaveChanges()
    {
        $post = \Yii::$app->request->post();
        $this->Posts->updateFields($post['request_id'],$post);

        return \Yii::$app->controller->redirect('/posts');
    }

And when the request is executed, error comes to my console. In the JSE itself, I checked all the data, everything comes up correctly there, it turns out that the error is on the php side. I used var_dump before the return line, and in the request I always got success. It turns out that the problem is with the return, specifically with the redirect. But what could be wrong here and how can it be done differently?


Solution

  • You can use javascript to redirect the page. In the controller, return a response like this:

    use yii\helpers\Url;
    
    public function actionSaveChanges()
    {
        $post = \Yii::$app->request->post();
        $this->Posts->updateFields($post['request_id'], $post);
        return $this->asJson([
            'url' => Url::to('/posts')
        ]);
    }
    

    In js, change your code like this:

    requestSend: function(e){
    let data = {
        request_id: e.target.dataset.request_id
    };
    $.ajax(
    {
        url: '/posts/save-changes',
        method: 'post',
        dataType: 'html',
        data: data,
        success: function(result)
        {
        window.location.href = result.url
        },
        error: function()
        {
            console.log('error');
        }
    });
    },