JavaScript, when used on its own, cannot interact directly with a MySQL database. Since JavaScript runs on the client-side (in the browser), and databases reside on the server-side, an intermediate server-side language is necessary to perform database queries. Examples of such languages include PHP, Java, .Net, and server-side JavaScript stacks like Node.js.
To integrate JavaScript, a server-side language, and MySQL, one can use AJAX (Asynchronous JavaScript and XML). Here's how it works:
<code class="javascript">var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", "phpfile.php", true); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");</code>
<code class="javascript">var data = "name=John&age=30";</code>
<code class="javascript">xmlhttp.send(data);</code>
<code class="php"><?php $name = $_POST['name']; $age = $_POST['age']; // Connect to the MySQL database $conn = mysqli_connect('localhost', 'username', 'password', 'database'); // Prepare the SQL query $sql = "INSERT INTO users (name, age) VALUES ('$name', '$age')"; // Execute the query $result = mysqli_query($conn, $sql); if ($result) { echo "Data saved successfully"; } else { echo "Error saving data"; } // Close the connection mysqli_close($conn); ?></code>
With this setup, when the JavaScript code executes the AJAX call, the data (user's name and age) is sent to the server-side PHP script. This script then connects to the MySQL database, executes an SQL query to insert the data into a database table, and returns a response indicating whether the data was saved successfully.
Note: The specific implementation details and syntax may vary depending on the server-side language and the database system being used.
The above is the detailed content of How to Send Data from JavaScript to a MySQL Database without Direct Connection?. For more information, please follow other related articles on the PHP Chinese website!