When working with web applications, it's often necessary to transfer data between JavaScript and PHP. One common scenario arises when handling JavaScript values, such as user input or calculations, and storing them in a MySQL database using PHP.
To accomplish this, let's consider a specific example: Assuming you have a JavaScript variable "lugar" containing latitude and longitude coordinates obtained from Google Maps:
<code class="javascript"><script> ... var lugar = results[0].geometry.location;// this gives me a latitud, longitud value, like: -34.397, 150.644 ... </script></code>
Our goal is to pass this value to the PHP variable "$lugar" to save it in the database. Here's how:
Utilizing jQuery's AJAX capabilities, we can send the "lugar" variable to a PHP script:
<code class="javascript"><script> $.ajax({ url: "save.in.my.database.php", type: "post", dataType:"json", data: { lugar: results[0].geometry.location }, success: function(data){ alert('saved'); }, error: function(){ alert('error'); } }); </script></code>
The "save.in.my.database.php" script, written in PHP, will receive the "_POST['lugar']_" variable:
<code class="php"><?php $lugar = $_POST['lugar']; // Connect to your MySQL database and execute a query to save the '$lugar' variable ?></code>
This script will handle the database operations for storing the JavaScript variable "lugar", completing the process of passing data between the frontend (JavaScript) and the backend (PHP).
The above is the detailed content of How to Transfer JavaScript Variables to PHP for Database Storage?. For more information, please follow other related articles on the PHP Chinese website!