0

I am trying to redirect in one of program but failed.I tried making a simple program where on a click of submit button it should redirect to another page. I must be making some very fundamental mistake but could not get it figured out.

I have a simple page where a form is created with an input box and submit button. On click of button a jquery is invoked which just redirect it to another page.

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
 <h1>Testing Redirection in Jquery</h1>

 <form method="POST" id="redirectForm" name="redirectForm">
  <input type="text" id="extraField" name="extraField"/><br/><br/>
  <input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
 </form>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"> 
 </script>
 <script>
  $(document).ready(function () {
   $("#btnSubmit").click(function (e) {
     alert("Start");
     var extraField = document.getElementById("extraField").value;
     try { 
       window.location.replace("page2.php"); 
       console.log("Successful");
     } 
     catch(e) { 
       window.location = "page2.php";
       console.log("Failed");                   
     }
    });
   });
 </script>
</body>
</html>

It just failed to redirect to page2.php rather it remains on the same page. I put the console.log as well it shows successful for a second and goes away. It shows no error as such.

Please help me to figure out the problem.

  • 4
    Possible duplicate of [How do I redirect to another webpage?](https://stackoverflow.com/questions/503093/how-do-i-redirect-to-another-webpage) – Koen Hollander Jan 28 '19 at 08:55

1 Answers1

1

You code execute 2 separate calls. 1) OnSubmit 2) OnClick

here your "submit call" execute 1st. If you want to proceed with redirect concept then you have to use type="button" instead of type="submit".

That`s why your call redirect on same page and it looks like code not working

Ashu
  • 1,320
  • 2
  • 10
  • 24