Home  >  Article  >  Database  >  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
Mary-Kate OlsenOriginal
2024-10-30 08:22:03443browse

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>

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);
}

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!

Statement:
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