How do you pass data between JavaScript and PHP?

Barbara Streisand
Release: 2024-11-01 02:06:28
Original
691 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!