Home > Database > Mysql Tutorial > How can I send data from JavaScript to a MySQL database?

How can I send data from JavaScript to a MySQL database?

Mary-Kate Olsen
Release: 2024-10-30 08:22:03
Original
519 people have browsed it

How can I send data from JavaScript to a MySQL database?

How do I send data from javascript to a mysql database?

JavaScript, by itself, cannot directly communicate with MySQL databases because they operate on different computers. JavaScript runs on the client side (in the browser), while databases typically reside on the server side.

Solution:

To establish communication between JavaScript and MySQL, you need an intermediary server-side language such as PHP, Java, or Node.js. This server-side language acts as a bridge to execute the MySQL query and return the results or store the data in the database.

Example using PHP:

<code class="php"><?php
$name = $_POST['name'];
$location = $_POST['location'];
$con = mysql_connect('localhost', 'peter', 'abc123');
$sql = "INSERT INTO user (name, location) VALUES ('$name', '$location')";
mysql_query($sql, $con);
mysql_close($con);</code>
Copy after login

This PHP code establishes a connection to the MySQL database, executes an insert query, and stores the data received from the JavaScript code.

Integrating with JavaScript:

In your JavaScript code, you can use AJAX (Asynchronous JavaScript and XML) to send the data to the server-side script. The AJAX request can be triggered by a button click or any other event:

function sendData() {
  const name = 'John Doe';
  const location = 'New York';
  const xhttp = new XMLHttpRequest();
  xhttp.open('POST', 'phpfile.php', true);
  xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhttp.send('name=' + name + '&location=' + location);
}
Copy after login

This JavaScript code creates an AJAX request, sets up the necessary headers, and sends the data to the PHP script via a POST request.

Conclusion:

By utilizing an intermediary server-side language, JavaScript can interact with MySQL databases by sending data and receiving results or updates. This integration allows you to create interactive web applications that can store and retrieve data from a database.

The above is the detailed content of How can I send data from JavaScript to a MySQL database?. 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