DEV Community

CoderLegion
CoderLegion

Posted on • Originally published at kodblems.com

How to redirect to another page in php on button click?

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)