Passing data between JavaScript and PHP can be necessary for various web development scenarios. This article addresses a specific use case where a JavaScript variable needs to be stored in a MySQL database via a PHP script.
Consider a situation where you obtain a latitude and longitude value from Google Maps in a JavaScript variable named lugar. The objective is to pass this variable to a PHP variable, also named lugar, and subsequently save it in a MySQL database.
To bridge the gap between JavaScript and PHP, you can utilize jQuery's Ajax function. This approach involves creating two JavaScript scripts.
JavaScript Script for Variable Transmission:
<code class="javascript">$.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'); } });</code>
PHP Script for Database Interaction:
<code class="php"><?php if(isset($_POST['lugar'])) { // DB connection and operations here // ... } ?></code>
Explanation:
Conclusion:
By leveraging jQuery's Ajax function and a separate PHP script, it is possible to transfer a JS variable (lugar) to a PHP variable ($lugar) and store its contents in a MySQL database. This technique enables seamless interaction between front-end JavaScript and server-side PHP code for data storage and management.
The above is the detailed content of How Do I Send a JavaScript Variable to a PHP Variable and Save It in MySQL?. For more information, please follow other related articles on the PHP Chinese website!