• 26 Jul, 2025

Advanced AJAX Contact Form with PHP Email – Modern UI & No Page Reload

Advanced AJAX Contact Form with PHP Email – Modern UI & No Page Reload

Learn how to build an advanced AJAX contact form with PHP that sends email without page reload. Includes modern UI design, form validation, and secure email handling using PHP's mail() function.

A clean, functional contact form is essential for any website. In this tutorial, you’ll learn how to build a beautiful and responsive contact form with AJAX that sends emails using PHP’s native mail() function—without refreshing the page.

By the end of this guide, you'll have:

  • A modern contact form UI
  • AJAX integration for seamless UX
  • Server-side email handling with validation

Let’s dive in!


What You’ll Need

  • A basic web server (XAMPP, WAMP, or a live server with PHP support)
  • HTML, CSS, JavaScript (AJAX)
  • Basic PHP knowledge

Step 1: Create the Contact Form (HTML + CSS)

contact.html

<form id="contactForm" class="contact-form">
  <h2>Contact Us</h2>
  <div class="input-group">
    <label for="name">Full Name</label>
    <input type="text" id="name" name="name" required />
  </div>
  <div class="input-group">
    <label for="email">Email</label>
    <input type="email" id="email" name="email" required />
  </div>
  <div class="input-group">
    <label for="subject">Subject</label>
    <input type="text" id="subject" name="subject" required />
  </div>
  <div class="input-group">
    <label for="message">Message</label>
    <textarea id="message" name="message" rows="5" required></textarea>
  </div>
  <button type="submit">Send Message</button>
  <p id="responseMessage"></p>
</form>

styles.css

body {
  font-family: 'Segoe UI', sans-serif;
  background: linear-gradient(135deg, #a1c4fd, #c2e9fb);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  min-height: 100vh;
}

.contact-form {
  background: white;
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.15);
  width: 100%;
  max-width: 500px;
}

.input-group {
  margin-bottom: 15px;
}

.input-group label {
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.input-group input,
.input-group textarea {
  width: 100%;
  padding: 10px;
  border-radius: 10px;
  border: 1px solid #ccc;
}

button {
  width: 100%;
  padding: 12px;
  background: #007BFF;
  color: white;
  font-weight: bold;
  border: none;
  border-radius: 10px;
  cursor: pointer;
}

button:hover {
  background: #0056b3;
}

Step 2: Add JavaScript for AJAX Handling

Inside <script> tag or main.js:

document.getElementById("contactForm").addEventListener("submit", function (e) {
  e.preventDefault();

  const formData = new FormData(this);
  const responseMessage = document.getElementById("responseMessage");

  fetch("send_mail.php", {
    method: "POST",
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    responseMessage.textContent = data.message;
    responseMessage.style.color = data.success ? "green" : "red";
    if (data.success) this.reset();
  })
  .catch(() => {
    responseMessage.textContent = "Something went wrong. Please try again.";
    responseMessage.style.color = "red";
  });
});

Step 3: Handle Email Sending with PHP

send_mail.php

<?php
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name    = htmlspecialchars(trim($_POST['name'] ?? ''));
    $email   = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $subject = htmlspecialchars(trim($_POST['subject'] ?? ''));
    $message = htmlspecialchars(trim($_POST['message'] ?? ''));

    if (!$name || !$email || !$subject || !$message) {
        echo json_encode(["success" => false, "message" => "All fields are required."]);
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(["success" => false, "message" => "Invalid email address."]);
        exit;
    }

    $to = "you@example.com"; // Change this!
    $headers = "From: $name <$email>\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

    $body = "New message received:\n\n";
    $body .= "Name: $name\nEmail: $email\nSubject: $subject\n\nMessage:\n$message\n";

    if (mail($to, $subject, $body, $headers)) {
        echo json_encode(["success" => true, "message" => "Message sent successfully!"]);
    } else {
        echo json_encode(["success" => false, "message" => "Failed to send. Try again."]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Invalid request method."]);
}
?>

Security & Reliability Tips

  • ✅ Sanitize all inputs server-side
  • ✅ Use filter_var() to validate email format
  • ✅ Switch to PHPMailer or SMTP for production (more reliable than mail())
  • ✅ Add a CAPTCHA (like Google reCAPTCHA) to prevent spam
  • ✅ Store a copy of submissions to a database for backup

Final Thoughts

With this setup, you've built a responsive, modern contact form that uses AJAX for a seamless user experience and PHP to send emails efficiently. This method works well for small- to medium-sized sites.

Want more advanced functionality? Consider:

  • Sending auto-reply confirmation emails
  • Logging messages to a database
  • Adding input animations and validation feedback

Y2A Post

Discover the innovative work in AI-generated blogs, seamlessly blending technology with creativity. This unique approach not only offers fresh perspectives on various topics but also ensures that content is engaging and relevant.