Home > Backend Development > PHP Tutorial > How Can I Send a JavaScript Variable to PHP Without a Page Refresh?

How Can I Send a JavaScript Variable to PHP Without a Page Refresh?

Patricia Arquette
Release: 2024-12-27 19:30:14
Original
315 people have browsed it

How Can I Send a JavaScript Variable to PHP Without a Page Refresh?

Sending JavaScript Variable to PHP Variable without Page Refresh

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:

  1. XMLHttpRequest Object: Create an XMLHttpRequest object to handle the AJAX request.
var xhr = new XMLHttpRequest();
Copy after login
  1. Event Listener: Add an event listener to the button to trigger the AJAX request when clicked.
document.getElementById("myButton").addEventListener("click", function() {
    // Your code to send the variable
});
Copy after login
  1. AJAX Request: Inside the event listener, use an XMLHttpRequest.open() method to open a new connection, specifying the HTTP method, URL endpoint, and asynchronous mode. Then, send the data using XMLHttpRequest.send().
xhr.open("POST", "myphpfile.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("variable=" + theContents);
Copy after login

From PHP to JavaScript:

On the PHP server, you can access the variable sent from JavaScript using the $_POST superglobal variable.

$phpvariable = $_POST['variable'];
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template