0

I am having trouble redirecting from one page to another on button click using javascript?

say, for example, one page is index.php and another is sub-page.php, how can I redirect to the subpage from the home page using javascript? can anyone please guide me? files are located in the root directory of my project.

I had already tried following code but it is not working :

HTML code :

<button type="button" onclick="test()">click me</button>

js code :

function test(){
 window.location.href = "./sub-page.php";
}
3
  • 1
    Please be more descriptive than just "not working". What actually happens? Is sub-page.php located in the document root or under some sub folder? Commented Jun 10, 2021 at 5:35
  • Maybe the path to the sub-page.php is not right. You can also use window.open("sub-page.php", "_self"); Commented Jun 10, 2021 at 5:45
  • 3
    Why would you want to abuse a button, for what is clearly a link’s job? Commented Jun 10, 2021 at 6:37

4 Answers 4

4

You Can use this .

<script>window.location.href = "/sub-page.php";</script>

<script>window.location.href = "http://www.google.com";</script>
Sign up to request clarification or add additional context in comments.

Comments

3

window.location.href = "sub-page.php";

Comments

3

First check for the right path for the sub-page You can also use window.open.

function test(){
    window.open("sub-page.php", "_self")
}

Comments

2

Is there any error in the browser's console?

If not, what you can do is put some "console.log" messages within your function, like

function test(){
 console.log("before href");
 window.location.href = "./sub-page.php";
 console.log("after href");
}

That way, you can tell if your function is being called correctly, by looking at the console output.

Always try to at least find an error message, instead of just saying it is not working. We will not be able to help you much with just a "not working".

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.