Home > Article > Backend Development > How do you pass data between JavaScript and PHP?
Passing Data Between Javascript and PHP
In web development, it's often necessary to transfer data between the client (Javascript) and the server (PHP). Here's how you can achieve this two-way communication:
From Javascript to PHP
To pass data from a Javascript script to a PHP page, you can use an HTTP request. This can be accomplished with the XMLHttpRequest object, as seen in the following example:
<code class="javascript">const httpc = new XMLHttpRequest(); const url = "get_data.php"; httpc.open("POST", url, true); httpc.onreadystatechange = function() { if(httpc.readyState == 4 && httpc.status == 200) { console.log(httpc.responseText); // process the response from PHP } }; const params = {tohex: 4919, sum: [1, 3, 5]}; httpc.send(JSON.stringify(params)); // send the data as JSON</code>
From PHP to Javascript
Passing data from a PHP script back to a Javascript script requires generating a response that the Javascript can handle. This response can be in various formats, such as JSON or plain text. Here's an example of generating a JSON response:
<code class="php">$tohex = base_convert(4919, 16); $sum = array_sum([1, 3, 5]); $response = ["tohex" => $tohex, "sum" => $sum]; echo json_encode($response); // output the JSON response</code>
Example Usage
An example of a Javascript script making a request to a PHP script and receiving the response would look like this:
<code class="javascript">async function requestData() { const response = await fetch("get_data.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({tohex: 4919, sum: [1, 3, 5]}) }); const {tohex, sum} = await response.json(); // parse the JSON response console.log(tohex, sum); // use the data returned from PHP } requestData();</code>
By combining these techniques, you can effectively pass data between Javascript and PHP, facilitating dynamic interactions between the client and server.
The above is the detailed content of How do you pass data between JavaScript and PHP?. For more information, please follow other related articles on the PHP Chinese website!