1

I wanted to implement redirection after getting successful response from server. I tried to do it the same way as described here, but unfortunately couldn't achieve the desired behavior.

The function which sends the data to the server and is supposed to perform redirection is the following:

 $("#btn-login").click(function(){
                if ($('#loginform').valid() == false) {
                    return false;
                }
                var formData = $("form#loginform").serialize();
                $.ajax({
                    type: "POST",
                    url: "/authentication/login",
                    data: formData,
                    success: function(data, textStatus){
                        console.log(formData);
                        //console.log(data);
                        if(data.redirect){
                            window.location.href = data.redirect;
                        }
                    },
                    error: function(e){
                        alert(e.responseText);
                    }
                });
            });

On the server side, the followoing function is executed:

/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
    successRedirect: '/',
    failureRedirect: '/authentication',
    failureFlash : true
}));

Does anyone know why the function on client does not redirect after receiving response from the server?

Thanks!

Community
  • 1
  • 1
Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286

1 Answers1

1

What is the output of console.log(data)?

It seems the server is redirecting so when the front end code recieves the output from the server, it is already the either the successRedirect or failureRedirect page, so your code window.location.href = data.redirect is not reached. Check data, it should have the redirect property. If not, my guess is that the server is already doing the redirect and you are not seeing it because you are calling it via ajax. This can be confirmed in the network tab of the web inspector.

Juank
  • 6,096
  • 1
  • 28
  • 28
  • data is actually html source of the page on location to which should be redirected. – Niko Gamulin Jul 10 '15 at 11:51
  • that confirms that the server is doing the redirecting, let me check the passport lib documentation as to how to return a json response instead of redirecting. This way you can login via ajax and redirect yourself – Juank Jul 10 '15 at 11:53
  • Check the custom callback section on http://passportjs.org/docs. This way you can return a json from your server instead of a redirect, something like `{redirect: 'mySecurePageRoute'}`. Now in your ajax response you should get a json object, not a bunch of html – Juank Jul 10 '15 at 11:56