π Before you dive into this article...
π Check out our vibrant new community at CoderLegion.com!
π‘ Share your knowledge, connect with like-minded developers, and grow together.
π Click here to join now!
Problem
I build some kind of interactive menu using PHP, HTML and JavaScript. I need redirect the page on click to some URL. Itried the following code, but it does not work:
" />
What is wrong with my code?
Solution
The root cause of the issue is, that you are trying to call PHP (server-side) code from JavaScript (the client-side). When JavaScript is acting β PHP (the server-side code) does not exist. It can be called during the server-side page rendering page only. Getting back to the original problem code sample, the statement:
<?php header("Location: /start.php");
will cause a JavaScript error, since it is not a valid JavaScript. What you can do? In case the βStartβ button should always redirect to start.php you can redirect the browser to the static URL, like that:
Markup
Start
JavaScript
var btn = document.getElementById('btnStart');
btn.addEventListener('click', function() {
document.location.href = 'start.php';
});
Another approach will be to use inline JavaScript
Start
Incase the URL is dynamic β it is up to server to decide what should be the redirect URL, the inline approach will be easier to implement:
ββ>Start
This technique called inline PHP, the server will generate the output, the browser will receive the following line:
Start
You can use the inline PHP in the JavaScript section (the first example) as well:
Markup
Start
JavaScript
var btn = document.getElementById('btnStart');
btn.addEventListener('click', function() {
document.location.href = '<?php echo "Stasrt.php"?>';
});
Tip:
There is a short cut for <?php echo β¦ , you can use <?=βtextβ?> instead. For example:
'">Start
So, there are several ways to redirect pages from the client-side, choose the one you like more.
Top comments (0)