Submit HTML Form with jQuery AJAX and PHP
The default behavior of HTML form submission is to submit the from to URL provided in action attribute of form when user clicks the submit button of form. Learn how to submit HTML form using AJAX in jQuery.

An HTML form is by default submitted to provided URL in action attribute of form. The form processing then takes place on script found on that URL and user is either redirected to a new success page or back to the same page. However this default behavior can be prevented and form can be submitted with AJAX request without requiring the page reload. This post demonstrates how to implement AJAX form submit with jQuery and PHP. The files we need to create for this post:
- constants.php: Constants for database connection.
- index.html: The HTML page containing the form.
- javascript.js: Code to submit form in JavaScript with jQuery AJAX.
- ajax-form-submit.php: The PHP server-side script for form processing.
- style.css: The CSS stylesheet for HTML page and form.
We will create an HTML page with form fields for minimal employee details and submit form using AJAX with jQuery. In server-side script we will add the record to database.
Add Constants to Connect to Database
We need to define some database configuration constants to connect to database. Create a PHP file to define database connection constants.
constants.php
<?php
define('DB_HOST', 'DATABASE_HOST'); // Your database host
define('DB_NAME', 'DATABASE_NAME'); // Your database name
define('DB_USER', 'DATABASE_USERNAME'); // Username for database
define('DB_PASSWORD', 'DATABASE_PASSWORD'); // Password for database
Create an HTML Page for AJAX Form
We need an HTML interface with form which user can fill and submit. Create an HTML page with form containing minimal fields for employee. We will submit form using AJAX for server-side processing.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Submit HTML Form with jQuery AJAX and PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport" />
<link rel="stylesheet" href="css/style.css" />
<script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
<script src="js/javascript.js" type="text/javascript"></script>
</head>
<body>
<section class="section py-4">
<div class="container">
<form action="ajax-form-submit.php" method="POST" class="employee-form">
<div class="mb-4">
<label class="inline-block mb-1">Full name: <span class="text-red">*</span></label>
<input type="text" name="full_name" class="form-control" required="required" placeholder="Full name..." />
</div>
<div class="mb-4">
<label class="inline-block mb-1">Email address: <span class="text-red">*</span></label>
<input type="email" name="email" class="form-control" required="required" placeholder="Email address..." />
</div>
<div class="mb-4">
<label class="inline-block mb-1">Designation: <span class="text-red">*</span></label>
<input type="text" name="designation" class="form-control" required="required" placeholder="Designation..." />
</div>
<div class="mb-4">
<label class="inline-block mb-1">Gender: <span class="text-red">*</span></label>
<div>
<label>
<input type="radio" name="gender" value="male" checked="checked">
Male
</label>
<label>
<input type="radio" name="gender" value="female">
Female
</label>
</div>
</div>
<div class="mb-4">
<button type="submit" class="btn btn-blue">Send</button>
</div>
</form>
</div>
</section>
</body>
</html>
AJAX Form Submit with jQuery
We handle the form submission on client-side by preventing the default form submission behavior and submit it using jQuery AJAX.
- Add an event listener for form submit after document has loaded.
- Prevent the default form submission behavior with
e.preventDefault()function. - Assign form to a variable.
- Submit form using jQuery's
$.ajax()method. - Set the type to
POSTand define a URL for form processing on server side. - Set form data with
form.serializeArray()method of jQuery. - On success reset the form and show an
alert()with success message. - Show the error message with an
alert()on error.
javascript.js
$(document).ready(function () {
$(".employee-form").on("submit", function (e) {
e.preventDefault();
let form = $(this);
$.ajax({
type: "POST",
url: "ajax-form-submit.php",
data: form.serializeArray(),
success: function (res, status, xhr) {
let result = JSON.parse(res);
if (result.success) {
form.get(0).reset();
alert(result.message);
}
},
error: function (xhr, status, error) {
let response = JSON.parse(xhr.responseText);
alert(response.message);
}
});
});
});Process AJAX Form Submit in PHP
Once the form is submitted from client-side to server we handle the form submission on server-side in PHP script. Create a PHP script file that contains the code to process AJAX form data and add record to database. The steps to process AJAX form submit in PHP are as follow:
- Connect to database with
mysqli_connectfunction. - Return JSON response with
success = 0if request is not an AJAX request. - Sanitize
$_POSTarray usingfilter_input_arraymethod of PHP. - Prepare a
$dataarray for employee record from the fields submitted via AJAX. - Insert the employee data using
mysqli_queryfrom the$dataarray previously prepared. - Return JSON success response if data was successfully added to database table.
- At the end set HTTP response code to 400 and return a JSON error message as a fallback for any case not handled.
ajax-form-submit.php
<?php
include_once 'constants.php';
$db_connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_connect_error());
// Get requested with header from $_SERVER
$request_with = strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? null);
// Return bad request code if it is not an AJAX request
if (empty($request_with) || $request_with !== 'xmlhttprequest') {
http_response_code(400);
die(json_encode([
'success' => 0,
'message' => 'Only AJAX request allowed'
], JSON_PRETTY_PRINT));
}
// Sanitize input array
$post = filter_input_array(INPUT_POST);
if (!empty($post)) {
$data = [];
$data['full_name'] = trim($post['full_name']);
$data['email'] = trim($post['email']);
$data['gender'] = trim($post['gender']);
$data['designation'] = trim($post['designation']);
$sql = sprintf('INSERT INTO employees (%s) VALUES (%s)',
implode(',', array_keys($data)),
implode(',', array_fill(0, count($data), '?')));
$stmt = mysqli_prepare($db_connection, $sql);
mysqli_stmt_bind_param($stmt, str_repeat('s', count($data)), ...array_values($data));
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
if (intval(mysqli_insert_id($db_connection))) {
die(json_encode([
'success' => 1,
'message' => 'Form has been processed successfully'
], JSON_PRETTY_PRINT));
}
}
http_response_code(400);
// Fallback to unknown error
die(json_encode([
'success' => 0,
'message' => 'Something went wrong! Please try again'
], JSON_PRETTY_PRINT));
Add AJAX Form CSS Styles
Finally, we add some CSS styles for AJAX form and entire HTML page.
style.css
* {
box-sizing: border-box;
}
html,body {
margin: 0;
padding: 0;
}
body {
background-color: #f6f6f6;
font-family: "Segoe UI", "Roboto", "Helvetica", sans-serif;
font-size: 15px;
font-weight: normal;
font-style: normal;
}
.container {
width: 100%;
max-width: 1140px;
margin-right: auto;
margin-left: auto;
padding-right: 15px;
padding-left: 15px;
}
.inline-block {
display: inline-block;
}
.py-4 {
padding-top: 1rem;
padding-bottom: 1rem;
}
.my-1, .mb-1 {
margin-bottom: .25rem;
}
.my-4, .mt-4 {
margin-top: 1rem;
}
.my-4, .mb-4 {
margin-bottom: 1rem;
}
.form-control {
display: block;
width: 100%;
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #3b3b3b;
background-color: #ffffff;
background-clip: padding-box;
border: 1px solid #d1d2d3;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.btn {
display: inline-block;
padding: 5px 10px;
cursor: pointer;
font: inherit;
}
.btn-blue {
background-color: #0369a1;
border: 1px solid #005D95;
color: #ffffff;
}Using the code in this post we are now able to prevent default form submission behavior using jQuery and submit form with AJAX. These code snippets can be used to prevent page reload and submit form with AJAX to maintain a better user experience and avoid reloading same resources.