What are the best practices for handling page redirection in PHP after a selection box change?
When handling page redirection in PHP after a selection box change, it is important to use JavaScript to capture the change event and send an AJAX request to a PHP script that will handle the redirection. This allows for a seamless user experience without having to reload the entire page.
// HTML code with selection box
<select id="selectionBox" onchange="redirectToPage()">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
// JavaScript function to handle selection box change and redirect
<script>
function redirectToPage() {
var selectedValue = document.getElementById("selectionBox").value;
var url = "redirect.php?page=" + selectedValue;
// AJAX request to redirect to the selected page
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
}
</script>
// PHP script (redirect.php) to handle the redirection
<?php
$page = $_GET['page'];
if ($page == "page1") {
header("Location: page1.php");
} elseif ($page == "page2") {
header("Location: page2.php");
}
?>