Question:
How can I send a JavaScript variable to a PHP variable, specifically when a button is clicked, and use it to retrieve data without refreshing the page?
Solution:
Although server-side languages like PHP and client-side languages like JavaScript operate separately, you can send JavaScript variables to PHP using AJAX techniques. Here's how:
From JavaScript to PHP:
var xhr = new XMLHttpRequest();
document.getElementById("myButton").addEventListener("click", function() { // Your code to send the variable });
xhr.open("POST", "myphpfile.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("variable=" + theContents);
From PHP to JavaScript:
On the PHP server, you can access the variable sent from JavaScript using the $_POST superglobal variable.
$phpvariable = $_POST['variable'];
Note: You can continue using the $phpvariable within your PHP code as needed, such as for database lookups.
The above is the detailed content of How Can I Send a JavaScript Variable to PHP Without a Page Refresh?. For more information, please follow other related articles on the PHP Chinese website!