Home > Article > Backend Development > 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 });
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>
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 }); });
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!