How to Submit a Form Using jQuery AJAX in PHP?
AJAX (Asynchronous JavaScript and XML) enhances user experience by allowing web pages to update asynchronously by exchanging data with the server behind the scenes. This guide will demonstrate how to submit a form using jQuery AJAX in PHP. We will cover creating the HTML form, handling form submission with jQuery AJAX, and processing the data in PHP to store it in a MySQL database.
Step 1 : Set Up Your Database and Table
Before handling form submissions, you need a database to store the collected data. We’ll use MySQL for this example.
CREATE DATABASE jquery_ajax_form_submission_db;
USE jquery_ajax_form_submission_db;
CREATE TABLE contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(15) NOT NULL,
gender VARCHAR(10) NOT NULL,
hobbies TEXT,
country VARCHAR(50) NOT NULL,
profile_picture VARCHAR(255) NOT NULL
);
Step 2 : Create the HTML Form
Let’s create an HTML form that includes different types of input fields. Save this as index.html
.
jQuery AJAX Form Submission Example
Contact Form
Step 3 : Create the PHP Script to Handle Form Submission
Next, create the submit_form.php
file to handle the form submission and store data in a MySQL database.
connect_error) {
die(json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]));
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize and validate input fields
$name = htmlspecialchars(strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = htmlspecialchars(strip_tags(trim($_POST["phone"])));
$gender = htmlspecialchars(strip_tags(trim($_POST["gender"])));
$hobbies = isset($_POST["hobbies"]) ? implode(", ", $_POST["hobbies"]) : "";
$country = htmlspecialchars(strip_tags(trim($_POST["country"])));
// Handle file upload
if (isset($_FILES["profile_picture"]) && $_FILES["profile_picture"]["error"] == 0) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["profile_picture"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file is an image
$check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
if ($check !== false) {
if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
$profile_picture = $target_file;
} else {
echo json_encode(['success' => false, 'message' => 'Sorry, there was an error uploading your file.']);
exit;
}
} else {
echo json_encode(['success' => false, 'message' => 'File is not an image.']);
exit;
}
}
// Insert data into the database
$sql = "INSERT INTO contacts (name, email, phone, gender, hobbies, country, profile_picture)
VALUES ('$name', '$email', '$phone', '$gender', '$hobbies', '$country', '$profile_picture')";
if ($conn->query($sql) === TRUE) {
echo json_encode(['success' => true, 'message' => 'Form data submitted successfully.']);
} else {
echo json_encode(['success' => false, 'message' => 'Error: ' . $conn->error]);
}
$conn->close();
} else {
echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
Conclusion :
Submitting forms using jQuery AJAX in PHP enhances the user experience by providing real-time feedback without reloading the page.
By following this guide, you can create and handle form submissions using jQuery AJAX in PHP, providing a seamless user experience.
Happy Coding!