The JavaScript Fetch API allows sending form data asynchronously to a PHP backend. PHP then inserts this data into a MySQL database using prepared statements, improving performance and user experience by avoiding page reloads.
The browser captures form submission, prevents default reload, sends data using Fetch, and PHP processes the request securely using PDO before returning a response.
// HTML form with Fetch API
<!DOCTYPE html>
<html>
<body>
<h3>Add New User</h3>
<form id="userForm">
<input type="text" name="name" placeholder="Enter name"><br>
<input type="email" name="email" placeholder="Enter email"><br>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("userForm").addEventListener("submit",function(e){
e.preventDefault();
let formData=new FormData(this);
fetch("insert.php",{method:"POST",body:formData})
.then(res=>res.text())
.then(data=>alert(data))
.catch(err=>console.error(err));
});
</script>
</body>
</html>
// PHP script using PDO
<?php
if($_SERVER["REQUEST_METHOD"]==="POST"){
$name=$_POST["name"]??"";
$email=$_POST["email"]??"";
try{
$pdo=new PDO("mysql:host=localhost;dbname=testdb","root","");
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$pdo->prepare("INSERT INTO users(name,email) VALUES(:name,:email)");
$stmt->bindParam(":name",$name);
$stmt->bindParam(":email",$email);
$stmt->execute();
echo "User inserted successfully!";
}catch(PDOException $e){
echo "Error: ".$e->getMessage();
}
}
?>
When the form is submitted, the data is sent without reloading the page. PHP inserts the record into the database and sends a success message back, which is displayed using an alert.
You can enhance this example by displaying success messages inside the page instead of alerts or by animating a loading spinner during submission.