Send FORMDATA OBJECT to a MYSQL Table using Vanilla JS

javascript

To send a FormData object to a MySQL table using vanilla JavaScript, you’ll need to use a combination of XMLHttpRequest (XHR) and PHP.

Here’s an example of how you can do it:

HTML form:

<form id="myForm">
  <input type="text" name="firstName" placeholder="First Name">
  <input type="text" name="lastName" placeholder="Last Name">
  <input type="submit" value="Submit">
</form>

JavaScript code to handle form submission:

const form = document.getElementById('myForm');

form.addEventListener('submit', (event) => {
  event.preventDefault(); // prevent form from submitting normally
  
  const formData = new FormData(form); // create a new FormData object from the form
  
  const xhr = new XMLHttpRequest(); // create a new XMLHttpRequest object
  
  xhr.open('POST', 'save.php', true); // specify the request method, URL, and asynchronous flag
  
  xhr.onload = function() { // callback function to handle the response
    if (xhr.status === 200) { // check if the response status is OK
      console.log(xhr.responseText); // log the response text to the console
    }
  };
  
  xhr.send(formData); // send the FormData object to the server
});

PHP code to handle the request and save the data to the MySQL table:

<?php

$servername = "localhost"; // replace with your server name
$username = "username"; // replace with your MySQL username
$password = "password"; // replace with your MySQL password
$dbname = "myDB"; // replace with your database name

// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Prepare the SQL statement
$stmt = $conn->prepare("INSERT INTO myTable (firstName, lastName) VALUES (?, ?)");
$stmt->bind_param("ss", $firstName, $lastName);

// Retrieve the form data
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];

// Execute the statement
if ($stmt->execute() === TRUE) {
  echo "Data saved successfully";
} else {
  echo "Error: " . $stmt->error;
}

// Close the statement and connection
$stmt->close();
$conn->close();

?>

In this example, we first select the form element using document.getElementById() and add an event listener to it using form.addEventListener() to handle the form submission. Inside the event listener, we create a new FormData object from the form using new FormData(form), create a new XMLHttpRequest object using new XMLHttpRequest(), and specify the request method, URL, and asynchronous flag using xhr.open().

We then define a callback function for the xhr.onload event that checks if the response status is OK and logs the response text to the console using console.log(xhr.responseText).

Finally, we send the FormData object to the server using xhr.send(formData).

On the server side, we create a new MySQL connection using new mysqli() and check the connection using $conn->connect_error. We then prepare an SQL statement using $conn->prepare() and bind the form data to the statement using $stmt->bind_param(). We retrieve the form data using $_POST and execute the statement using $stmt->execute(). If the execution is successful, we echo a success message; otherwise, we echo an error message. We then close the statement and connection using $stmt->close() and `$conn->close