views:

52

answers:

1

Hope you can help. A bit of a jQuery/AJAX newb here.

I have a basic SimpleModal login form that may be called from the homepage of my site.

login.js calls the login.php script that checks my database for a user's credentials.

If the login is successful I set a few session variables and I usually use the header command to send the user to their personal page (or the error page on login failure).

eg. header("Location:restricted/index.php");

I can't get the modal login form to close and the parent homepage to redirect to the member page. I'm usually left with the blank modal square saying "Thank You"

If i try to close the modal form with

success: function (data) {
 $('#login-container .login-loading').fadeOut(200, function () {
  $('#login-container .login-title').html('Thank you!');
  msg.html(data).fadeIn(200);
  $.modal.close(); //have inserted this line
 });
},

the modal closes but I am left on the homepage. (The user is logged in at this stage but the redirect has not happened).

I've been kicking this around for a day or 2. I had a look at the wordpress login plugin but I am none the wiser. Any ideas?

+2  A: 

Actually the redirect probably did happen, it just happened inside the AJAX request. When you do a redirect, the XmlHttpRequest that the ajax functions use transparently follows it, so then page that came back to the client is the restricted/index.php. what I tend to do is add a header on that page, something like this:

header("Redirect:restricted/index.php");

Then look for the header, something like this using $.ajaxSetup():

$.ajaxSetup({
  complete: function (xhr) {
    var redirect = xhr.getResponseHeader('Redirect');
    if(redirect) window.location.href = redirect;
  }
});

This way (unless you override complete, it leaves this option open) when a request comes back that made it to the restricted/index.php (remember the XmlHttpRequest actually went there) it'll get a header to let the client know it needs to redirect.

Nick Craver
Thanks for the reply. Yes the redirect is indeed happening behind the scenes. New to AJAX - it is hard to see what is happening. So I now have the > header("Redirect:restricted/index.php"); on the target page restricted/index.php and I now have the Redirect HTTP header. Exactly where should I put the ajaxSetup function and how do I call it. Sorry for such a stupid question. I have it in the page code with a >if (redirect) alert(redirect); debugging line within script tags but it is not running. Thanks!
@user438858 - How about *not* redirecting, and instead sending a different header to the client so *they* can redirect, like I have above...you just add that header if the login was successful?
Nick Craver
@user438858 - It can be called anywhere, just once is all you need, before you make any ajax requests. If the ajax requests have their own `complete` you need to change the approach a bit, is that the case?
Nick Craver