jQuery AJAX with PHP – Submit Form Without Page Reload

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:

  1. User fills the form and clicks submit
  2. jQuery prevents page reload using e.preventDefault()
  3. AJAX sends form data to a PHP file
  4. PHP processes the data and inserts it into the database
  5. Server sends a response back
  6. 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

ProblemSolution
Page reloadsUse e.preventDefault()
No responseWrong file path or URL
DB errorIncorrect DB credentials
Data emptyMissing name attributes in inputs
AJAX not workingjQuery not loaded

Real-World Use Cases

  • Contact forms
  • Login & registration
  • Comments system
  • Live feedback forms

FAQs

What is jQuery AJAX in simple terms?

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.

Why use AJAX for form submission?

AJAX lets you submit forms without refreshing the page, which improves user experience and makes the application feel faster.

Can I use jQuery AJAX without PHP?

Yes, jQuery AJAX can work with any backend like Node.js, Python, or APIs. PHP is just one common option for server-side processing.

Is jQuery AJAX still useful in 2026?

Yes, especially for WordPress development, legacy projects, and simple applications. However, modern projects often use Fetch API or frameworks.

How do I prevent page reload in AJAX form submission?

You can prevent page reload using:

e.preventDefault();

Why is my AJAX request not working?

Common reasons:
Wrong file path
jQuery not loaded
Server not running (PHP requires server)
JavaScript errors in console

Is it safe to insert data directly into the database?

No. Always use prepared statements to avoid SQL injection attacks.

What is the difference between $.post() and $.ajax()?

$.post() → Shortcut method (simpler)
$.ajax() → More flexible and customizable

Mini Task for Students

  1. Add phone number field
  2. Validate email using jQuery
  3. Show loading text while submitting
  4. 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.

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *