javascript tutorial - [Solved-5 Solutions] How do we redirect with javascript ? - javascript - java script - javascript array
Problem:
How do we redirect to a page from another page with javascript ?
Solution 1:
To redirect to another page, we can use:
window.location = "http://www.yoururl.com";
click below button to copy the code. By JavaScript tutorial team
Solution 2:
window.location.replace('http://sidanmor.com');
click below button to copy the code. By JavaScript tutorial team
It's better than using window.location.href = 'http://sidanmor.com';
Using replace() is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If we want to simulate someone clicking on a link, use location.href. If we want to simulate an HTTP redirect, use location.replace.
If we want to simulate someone clicking on a link, use window.location.href
If we want to simulate an HTTP redirect, use window.location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");
// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";
click below button to copy the code. By JavaScript tutorial team
Solution 3:
We can't redirect to a function. What we can do is pass some flag on the URL when redirecting, then check that flag in the server side code and if raised, execute the function. For example:
document.location = "MyPage.php?action=DoThis";
click below button to copy the code. By JavaScript tutorial team
Then in our PHP code check for "action" in the query string and if equal to "DoThis" execute whatever function we need.
Solution 4:
- If we want to simulate someone clicking on a link, use location.href.
- If we want to simulate an HTTP redirect, use location.replace.
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://wikitechy.com");
// similar behavior as clicking on a link
window.location.href = "http://wikitechy.com";
click below button to copy the code. By JavaScript tutorial team
Solution 5:
Compared to window.location="url";
it is much easyer to do just location="url";
WE always use that