Redirect after ajax request

Hi guys,

I have this kind of problem. When I try to use redirect() triggered by an ajax request it kills the session and logs me out.

Hope you can help me with my problem :rolleyes:

I am using Yii v.1.10 in my aplication, but it behaves the same on v.1.3 and v.1.11.

[I can’t post any real code from this aplication cause it is someone else intelectual property.]

remake the problem area as simple separate project not revealing the confidential stuff.

It goes like that:

  1. In the View I want to send through AJAX: $.post(‘index.php?r=controller/someAction’) + {JSON data};

  2. And then in action at the end I want to redirect to some other View, lets say: $this->redirect(array(’/system/settings’));

When I do it like that, through AJAX, it kills session and redirects to Login View.

It is hard for me to tell what causes that. I hope you can throw me some ideas why is this happening so I could at least know where to look.

Why not just redirect from javascript after the ajax call.

document.location = 'redirect here';

There must be something killing the session either before the redirect, or perhaps in the controller/action that the redirect points to.

Try redirecting to another controller that will simply echo ‘hello’ or whatever and see if your session still breaks. Then you know where the error is. My guess is something in “/system/settings”.

It’s not a good idea to redirect (send Headers), on AJAX requests. Why don’t you try something like this

  1. in your target controller

public function actionSomeAction(){



        //do something

        //Some true / false logic


            //add a status code to the json array

            echo CJSON::encode(array('status'=>'200', 'redirect'=>Yii::app()->createUrl('/controller/action/')));


            echo CJSON::encode(array('status'=>'500', 'redirect'=>Yii::app()->createUrl('/error/action/')));



And your JavaScript could look like this

$.post(url, function(data){

    //get the url

    redirect = data.redirect

    //if everything is OK, redirect to that url

    if(data.status == '200')

        window.location.href = redirect


        //if not, do something...


}, 'json')