Noah Noah - 3 years ago 255
Ajax Question

Symfony2 redirect in an ajax action

I am using Symfony2 and in my register.html.twig, I have:

var registerdata= {
"email": email,
"pwd": pwd,
"phoneNum": phoneNum
};
$.ajax({
type: 'POST',
url: "register",
data: registerdata,
success: function(msg){

alert("OK! ");
},
error: function(XmlHttpRequest,textStatus, errorThrown){

alert("Failed! ");
}
});


In my controller, after inserting those data into the database, I want to redirect to the login page, and I have code like this:

try
{
$this -> insertData($account);
return $this ->redirect($this ->generateUrl('login'));
}
catch (Exception $e)
{
return new response('Message: '. $e->getMessage());
}


It does not work, however. How should I handle the problem?

Answer Source

You need another more step in your jQuery code. When the server returns a redirect response, you should redirect the client using javascript:

var registerdata= {
    "email": email,
    "pwd": pwd,
    "phoneNum": phoneNum
    };
$.ajax({
    type: 'POST',
    url: "register",
    data: registerdata,
    success: function(msg){

        alert("OK! ");
    },
    error: function(XmlHttpRequest,textStatus, errorThrown){

        alert("Failed! ");
    },
    complete: function(xhr)
    {
        if (xhr.status == 302) {
            location.href = xhr.getResponseHeader("Location");
        }
    }
});

Of course this is far from ideal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download