AJAX allows web pages to communicate with the server asynchronously. Using PHP and AJAX together enables inserting database records without refreshing the page, improving user experience in modern web applications.
The browser sends form data using an AJAX request. PHP receives the request, validates and sanitizes the input, then inserts the record into the database and returns a response.
// HTML form and AJAX submission logic
<form id="dataForm">
<label>Name:</label>
<input type="text" id="name"><br><br>
<label>Email:</label>
<input type="text" id="email"><br><br>
<button type="submit">Submit</button>
</form>
<div id="response"></div>
document.getElementById("dataForm").addEventListener("submit",function(e){
e.preventDefault();
var name=document.getElementById("name").value;
var email=document.getElementById("email").value;
var xhr=new XMLHttpRequest();
xhr.open("POST","insert.php",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onload=function(){
document.getElementById("response").innerHTML=xhr.responseText;
};
xhr.send("name="+name+"&email="+email);
});
// PHP script to insert form data into MySQL
<?php
$conn=new mysqli("localhost","username","password","database");
if($conn->connect_error){
die("Connection failed");
}
$name=mysqli_real_escape_string($conn,$_POST["name"]);
$email=mysqli_real_escape_string($conn,$_POST["email"]);
$sql="INSERT INTO users(name,email) VALUES('$name','$email')";
if($conn->query($sql)){
echo "Record inserted successfully";
}else{
echo "Error inserting record";
}
$conn->close();
?>
When the form is submitted, the data is sent to the server without page reload. The server inserts the record and sends a success or error message back to the page.
User → Form → AJAX Request → PHP Script → Database → Response Message