Submit HTML Form with jQuery AJAX and PHP

The default behavior of HTML form submission is to submit the form to the URL provided in the action attribute of the form when the user clicks the submit button. Learn how to submit an HTML form using AJAX in jQuery.

Submit HTML Form with jQuery AJAX and PHP

An HTML form is by default submitted to the provided URL in the action attribute of a form. The form processing then takes place in a script found on that URL, and the user is either redirected to a new success page or back to the same page. However, this default behavior can be prevented and the form can be submitted with an 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:

  1. constants.php: Constants for database connection.
  2. index.html: The HTML page containing the form.
  3. javascript.js: Code to submit form in JavaScript with jQuery AJAX.
  4. ajax-form-submit.php: The PHP server-side script for form processing.
  5. style.css: The CSS stylesheet for the HTML page and form.

We will create an HTML page with form fields for minimal employee details and submit the form using AJAX with jQuery. In the server-side script, we will add the record to the database.

 

Add Constants to Connect to Database

We need to define some database configuration constants to connect to the 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 a form that the user can fill out and submit. Create an HTML page with a form containing minimal fields for an employee. We will submit the 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 the client-side by preventing the default form submission behavior and submitting it using jQuery AJAX. 

  • Add an event listener for form submit after the document has loaded.
  • Prevent the default form submission behavior with the e.preventDefault() function.
  • Assign the form to a variable.
  • Submit form using jQuery's $.ajax() method.
  • Set the type to POST and define a URL for form processing on the server side.
  • Set form data with form.serializeArray() method of jQuery.
  • On success, reset the form and show an alert() with a 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 the client-side to the server, we handle the form submission on the server-side in a PHP script. Create a PHP script file that contains the code to process AJAX form data and add a record to the database. The steps to process an AJAX form submit in PHP are as follows:

  • Connect to the database with the mysqli_connect function.
  • Return JSON response with success = 0 if the request is not an AJAX request.
  • Sanitize $_POST array using the filter_input_array method of PHP.
  • Prepare a $data array for the employee record from the fields submitted via AJAX.
  • Insert the employee data using mysqli_query from the $data array previously prepared.
  • Return a JSON success response if data was successfully added to the database table.
  • At the end, set the 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 the AJAX form and the 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 the form with AJAX. These code snippets can be used to prevent page reload and submit a form with AJAX to maintain a better user experience and avoid reloading the same resources.