Inroduction
Submitting forms without reloading the page is a key feature of modern web applications. It improves user experience, makes websites faster, and creates smooth interactions.
Using jQuery AJAX with PHP, you can send form data to the server, process it, and store it in a database—all without refreshing the page.
In this step-by-step tutorial, you’ll learn how to submit a form using AJAX, handle it with PHP, and insert data into a MySQL database. This concept is widely used in contact forms, login systems, and WordPress development.
What You’ll Learn
- Submit form using AJAX
- Send data to PHP
- Insert data into MySQL
- Display success/error messages
- Prevent page reload
How AJAX Form Submission Works
Here’s a simple flow of how everything works:
- User fills the form and clicks submit
- jQuery prevents page reload using e.preventDefault()
- AJAX sends form data to a PHP file
- PHP processes the data and inserts it into the database
- Server sends a response back
- jQuery displays the response on the page
👉 This allows real-time interaction without refreshing the page.
Step 1: Create Database & Table
SQL Query
CREATE DATABASE ajax_demo;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Step 2: HTML Form
<form id="userForm">
<input type="text" name="name" placeholder="Enter Name" required>
<input type="email" name="email" placeholder="Enter Email" required>
<button type="submit">Submit</button>
</form>
<div id="message"></div>
Step 3: jQuery AJAX Form Submit
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('#userForm').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'insert.php',
type: 'POST',
data: $(this).serialize(),
success: function(response) {
$('#message').html(response);
$('#userForm')[0].reset();
}
});
});
</script>
Step 4: PHP – Database Connection
db.php
<?php
$conn = new mysqli("localhost", "root", "", "ajax_demo");
if ($conn->connect_error) {
die("Connection failed");
}
?>
Step 5: PHP – Insert Data
insert.php
<?php
include 'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql)) {
echo "Data inserted successfully!";
} else {
echo "Error inserting data";
}
?>
Step 6: Display Result Without Reload
When the form is submitted:
- Data is saved to database
- Success message appears
- Page does not reload
This is the power of AJAX 💡
When to Use AJAX Form Submission
Use AJAX when:
- You want a smooth user experience
- You don’t want page reloads
- You need real-time feedback
Avoid AJAX when:
- SEO content depends on form submission
- A simple form submit is enough
Improving Security (Important)
Use Prepared Statements
Never directly insert user input into SQL queries. This can lead to SQL Injection attacks.
Always use prepared statements:
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
Also consider:
- Validating inputs before sending
- Sanitizing data in PHP
- Using server-side validation
Common Errors & Fixes
| Problem | Solution |
|---|---|
| Page reloads | Use e.preventDefault() |
| No response | Wrong file path or URL |
| DB error | Incorrect DB credentials |
| Data empty | Missing name attributes in inputs |
| AJAX not working | jQuery not loaded |
Real-World Use Cases
- Contact forms
- Login & registration
- Comments system
- Live feedback forms
FAQs
jQuery AJAX allows you to send and receive data from the server without reloading the page. It helps create faster and more interactive web applications.
AJAX lets you submit forms without refreshing the page, which improves user experience and makes the application feel faster.
Yes, jQuery AJAX can work with any backend like Node.js, Python, or APIs. PHP is just one common option for server-side processing.
Yes, especially for WordPress development, legacy projects, and simple applications. However, modern projects often use Fetch API or frameworks.
You can prevent page reload using:
e.preventDefault();
Common reasons:
Wrong file path
jQuery not loaded
Server not running (PHP requires server)
JavaScript errors in console
No. Always use prepared statements to avoid SQL injection attacks.
$.post() → Shortcut method (simpler)
$.ajax() → More flexible and customizable
Mini Task for Students
- Add phone number field
- Validate email using jQuery
- Show loading text while submitting
- Store timestamp in database
Conclusion
jQuery AJAX with PHP is a powerful combination for building dynamic and interactive web applications.
By using AJAX, you can improve user experience, reduce page reloads, and handle form submissions efficiently.
Once you understand this concept, you can build advanced features like login systems, comment sections, and real-time updates.
