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

posted Originally published at kodblems.com 2 min read
**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


JavaScript

var btn = document.getElementById('btnStart');
btn.addEventListener('click', function() {
document.location.href = 'start.php';
});
Another approach will be to use inline JavaScript


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:


This technique called inline PHP, the server will generate the output, the browser will receive the following line:


You can use the inline PHP in the JavaScript section (the first example) as well:

Markup


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:


So, there are several ways to redirect pages from the client-side, choose the one you like more.

2 Comments

0 votes
0 votes

More Posts

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

prince yadav - Feb 17, 2024

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

Just completed another large-scale WordPress migration — and the client left this

saqib_devmorph - Apr 7

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

5 Web Dev Pitfalls That Are Silently Killing Your Projects (With Real Fixes)

Dharanidharan - Mar 3
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!