Posted on : January 5, 2025
How to Create a Contact Form Using HTML, JavaScript, and PHP with MySQL/MariaDB
Creating a functional contact form is an essential skill for web developers. In this tutorial, we’ll build a user registration form using HTML for the structure, JavaScript for client-side validation and AJAX submission, and PHP to handle server-side processing and interact with a MySQL/MariaDB database.
Prerequisites
Before diving in, ensure you have the following:
A working local server like XAMPP, WAMP, or MAMP.
Basic understanding of HTML, JavaScript, and PHP.
A MySQL/MariaDB database ready for integration.
Step 1: Setting Up the Project
File Structure
Organize your project files as follows:
/form-project
|-- form.html
|-- form.js
|-- form.phpDatabase Setup
Create a MySQL/MariaDB database:
1. Open phpMyAdmin or a database client.
2. Create a database named formtest.
3. Run the following SQL command to create a table:
CREATE TABLE form_datas (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
mobile VARCHAR(10) NOT NULL
);
Step 2: Building the HTML Form
Here’s the structure of our form in form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>User Registration</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Contact Form</h2>
<form id="registrationForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<span class="error" id="nameErr"></span>
<br /><br />
<label for="email">Email:</label>
<input type="text" id="email" name="email" />
<span class="error" id="emailErr"></span>
<br /><br />
<label for="mobile">Mobile:</label>
<input type="text" id="mobile" name="mobile" />
<span class="error" id="mobileErr"></span>
<br /><br />
<button type="submit">Submit</button>
</form>
<script src="./form.js"></script>
</body>
</html>
This form captures the user's name, email, and mobile number, with placeholders for displaying errors dynamically.
Step 3: Adding JavaScript for Validation and AJAX
Our JavaScript file, form.js handles:
1. Client-side validation.
2. AJAX submission using the fetch API.
JavaScript Code:
document
.getElementById("registrationForm")
.addEventListener("submit", function (e) {
e.preventDefault(); // Prevent default form submission
// Clear previous errors
document.getElementById("nameErr").innerText = "";
document.getElementById("emailErr").innerText = "";
document.getElementById("mobileErr").innerText = "";
// Collect form data
const formData = new FormData(this);
// Send data via AJAX
fetch("form.php", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
if (data.success) {
alert(data.message);
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("mobile").value = "";
} else {
// Display validation errors
document.getElementById("nameErr").innerText = data.nameErr || "";
document.getElementById("emailErr").innerText = data.emailErr || "";
document.getElementById("mobileErr").innerText = data.mobileErr || "";
}
})
.catch((error) => console.error("Error:", error));
});
This script prevents page reload, validates the form, and submits data via an AJAX request.
Step 4: Writing the PHP Script
The form.php script handles:
1. Server-side validation.
2. Database insertion.
PHP Code:
<?php
header('Content-Type: application/json');
// Initialize error and input variables
$nameErr = $emailErr = $mobileErr = "";
$name = $email = $mobile = "";
// Sanitize input
function test_input($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Validate inputs
if (empty($_POST["name"])) $nameErr = "Name is required";
else if (!preg_match("/^[a-zA-Z-' ]*$/", $_POST["name"])) $nameErr = "Only letters and white space allowed";
if (empty($_POST["email"])) $emailErr = "Email is required";
else if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) $emailErr = "Invalid email format";
if (empty($_POST["mobile"])) $mobileErr = "Mobile number is required";
else if (!preg_match("/^[0-9]{10}$/", $_POST["mobile"])) $mobileErr = "Invalid mobile number";
// Insert into database if no errors
if (!$nameErr && !$emailErr && !$mobileErr) {
$conn = new mysqli("localhost", "root", "", "formtest");
if ($conn->connect_error) {
echo json_encode(["success" => false, "message" => "Database connection failed"]);
exit;
}
$stmt = $conn->prepare("INSERT INTO form_datas (name, email, mobile) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $_POST["name"], $_POST["email"], $_POST["mobile"]);
$stmt->execute() ?
print(json_encode(["success" => true, "message" => "Registration successful"])) :
print(json_encode(["success" => false, "message" => "Database error"]));
$stmt->close();
$conn->close();
} else {
echo json_encode(["success" => false, "nameErr" => $nameErr, "emailErr" => $emailErr, "mobileErr" => $mobileErr]);
}
}
?>
This script validates inputs and inserts them into the database if no errors are found.
Step 5: Testing the Form
1. Open form.html in a browser.
2. Test form submission with valid and invalid inputs.
3. Check the database to ensure data is being inserted correctly.
Conclusion
Congratulations! You’ve built a fully functional contact form integrated with a MySQL/MariaDB database. This tutorial demonstrates the power of combining front-end and back-end technologies. Let us know if you encounter any issues in the comments below!
GitHub Link : https://github.com/Thirunavukarasan8489/how-to-post-a-data-using-html-javascript-php