How can PHP variables be passed through buttons to dynamically load content without refreshing the entire page?
To pass PHP variables through buttons to dynamically load content without refreshing the entire page, you can use AJAX to send the variables to a PHP script that fetches the content based on the variables and returns it to the page. This allows for seamless content loading without the need to reload the entire page.
// HTML code with buttons that pass variables to JavaScript function
<button onclick="loadContent('variable1')">Load Content 1</button>
<button onclick="loadContent('variable2')">Load Content 2</button>
// JavaScript function to send AJAX request with the variable to PHP script
function loadContent(variable) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML = this.responseText;
}
};
xhttp.open("GET", "load_content.php?variable=" + variable, true);
xhttp.send();
}
// PHP script (load_content.php) to fetch content based on the variable
<?php
$variable = $_GET['variable'];
// Fetch content based on the variable
$content = getContent($variable);
echo $content;
?>