2

The Problem

I can't seem to get the javascript to redirect after the php has echoed "Success".

Im basically just trying to make it where the javascript post my form data and then the usesr is redirected to their account page. I did have this being done via php, but I wanted the luxury of being able to stay on the same page while logging in.

The Javascript

 <script>
$(document).ready(function() {
//When the form with id="myform" is submitted...
$("#login_form").submit(function() {
     //Send the serialized data to formProcessor.php.
     $.post("login.php", $("#login_form").serialize(),
     //Take our repsonse, and replace whatever is in the "formResponse"
     //div with it.
    function(data) {
          if(data == "Success"){
          location.href="home";
      }
     }
);
return false;
});
});
</script>
15
  • 2
    Everytime I see ajax for a form submit, and then a javascript redirect, it makes my eyes hurt.
    – adeneo
    Jul 24, 2013 at 17:45
  • 3
    ^^^ What a strange concept, forms can be submitted ?
    – adeneo
    Jul 24, 2013 at 17:47
  • 1
    why echo back Success, why not just have php redirect on success, or echo back whatever error message you want when failed? By using echo('success'), a clever "user" could easily emulate it in console and get redirected without ever actually logging in!
    – SpYk3HH
    Jul 24, 2013 at 17:48
  • 1
  • 1
    FYI, PHP_Session and Cookies can be faked as well. Headers too. Using ajax to redirect based on "success" is just bad, I understand using to check for "failed login attempts", but you're better off handling all redirecting server-side. Not trying to argue, just some "constructive criticism"
    – SpYk3HH
    Jul 24, 2013 at 17:58

2 Answers 2

3

You redirect using document.location or window.location not location.href

window.location = "home.html";

// or 

document.location="home.html"; //Will not work on older IE Version

Note:

document.location was originally a read-only property which Gecko & Webkit browsers allowed to edit. For cross browser compatibility use window.location as it a read/write property.

2
  • 1
    Warning: document.location is a read-only property in older IE versions.
    – Jeff Noel
    Jul 24, 2013 at 17:58
  • @JeffNoel, Indeed should have included that too. I have updated my answer.
    – Starx
    Jul 25, 2013 at 2:00
2

You can try any one of this

Method 1:

window.location.replace("home.html");

Method 2:

window.location.href = "home.html";

Method 3:

$(location).attr('href',"home.html");

Hope this will help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.