Let’s create a more advanced PHP contact form with AJAX to handle form submission without refreshing the page.
This example assumes you have jQuery included in your project for simplicity. If you don’t have it, you can include it from a CDN or download it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function () {
$("#contactForm").submit(function (e) {
e.preventDefault(); // Prevent the form from submitting in the traditional way
// Serialize the form data
var formData = $(this).serialize();
// Make AJAX request
$.ajax({
type: "POST",
url: "process_form.php", // Change this to your PHP processing script
data: formData,
success: function (data) {
// Handle the successful response
$("#formResponse").html(data);
},
error: function (error) {
// Handle errors
console.error('Error:', error);
}
});
});
});
</script>
</head>
<body>
<div id="formResponse"></div>
<form id="contactForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
// process_form.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Validate form data (perform additional validation as needed)
if (empty($name) || empty($email) || empty($message)) {
echo "Please fill in all fields.";
} else {
// Process the form data (you can send an email, save to a database, etc.)
// For demonstration purposes, we'll just echo the received data
echo "Form submitted successfully!<br>";
echo "Name: $name<br>";
echo "Email: $email<br>";
echo "Message: $message";
}
} else {
echo "Invalid request method.";
}
?>
You should add more validation in this, security measures, and error handling based on your specific needs. Additionally, consider implementing proper email sending or storing the form data securely, depending on your use case.