How to Pass Data Between JavaScript and PHP?

DDD
Release: 2024-10-30 14:10:26
Original
484 people have browsed it

How to Pass Data Between JavaScript and PHP?

Passing Data Between JavaScript and PHP

When working with web applications, it's often necessary to exchange data between JavaScript and PHP. This can be done in two ways:

Passing data from JavaScript to PHP

To pass data from JavaScript to a PHP script, you can use a JavaScript request object (e.g., XMLHttpRequest in older browsers, fetch in modern browsers):

const data = {tohex: 4919, sum: [1, 3, 5]};
const params = new URLSearchParams(data);

fetch('server.php', {
  method: 'POST',
  body: params
}).then(res => {
  // Handle PHP response here
});
Copy after login

Passing data from PHP to JavaScript

To pass data back to the JavaScript script, you can use PHP's echo or json_encode functions to generate the response:

<code class="php">$tohex = ...; // Set this to data.tohex
$sum = ...; // Set this to data.sum

$response = array(base_convert($tohex, 16), array_sum($sum));
echo json_encode($response);</code>
Copy after login

In JavaScript, you can receive and parse the JSON response as follows:

fetch('server.php', {
  method: 'POST',
  ...
}).then(res => {
  res.json().then(data => {
    // Handle PHP response here
  });
});
Copy after login

By combining these techniques, you can seamlessly pass data between JavaScript and PHP to facilitate interactive web applications.

The above is the detailed content of How to 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
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!