Ajax Validation In PHP With Jquery Example Tutorial

May 08, 2024 | PHP jQuery MySql Ajax


Hello Dev,

In this article, I'd like to share a practical example of jQuery AJAX form validation from scratch. jQuery has gained immense popularity due to its versatility and power. I'll demonstrate server-side PHP validation coupled with jQuery AJAX requests to ensure a seamless user experience.

Let's start by creating a PHP "Contact Us" form using the Bootstrap framework for a sleek appearance. Upon clicking the "Send Message" button, an AJAX POST request will be triggered to validate the form fields. Any validation errors will be displayed without a page refresh, providing instant feedback to the user.

For this demonstration, we'll organize our code into two files:

1. index.php
2. formProcess.php

In the `index.php` file, we'll include jQuery and Bootstrap, structure the HTML layout, and incorporate necessary jQuery code. The `formProcess.php` file will handle the validation logic, returning JSON data as needed.

Let's delve into this straightforward example step by step.

To create a simple contact form using Bootstrap and validate it with jQuery AJAX before sending the data to a PHP script for processing, follow these steps. This example will demonstrate how to use Bootstrap for styling, jQuery for AJAX and form validation, and PHP for server-side processing.

Read Also: PHP MySQL Confirmation Box Before Delete Record Using Ajex Example Tutorial Step 1: Create the HTML Form

Create a file named index.php and add the following HTML code. This code includes Bootstrap for styling, jQuery for AJAX and form validation, and a simple form for user input.

index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax Validation In PHP With Jquery Example Tutorial -- ItErrorSolution.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <h2>Ajax Validation In PHP With Jquery Example Tutorial -- ItErrorSolution.com</h2>
    <form id="contactForm" novalidate>
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" required>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">Email</label>
            <input type="email" class="form-control" id="email" required>
        </div>
        <div class="mb-3">
            <label for="message" class="form-label">Message</label>
            <textarea class="form-control" id="message" rows="3" required></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Send Message</button>
    </form>
</div>

<script>
$(document).ready(function() {
    $('#contactForm').on('submit', function(e) {
        e.preventDefault();

        var name = $('#name').val();
        var email = $('#email').val();
        var message = $('#message').val();

        if (!name ) {
            alert('Name fields are required.');
            return;
        } else if(!email) {
            alert('Email fields are required.');
            return;
        } else if(!message) {
            alert('Message fields are required.');
            return;
        } else {
            alert('ok done');
            return;
        }

        $.ajax({
            url: 'formProcess.php',
            type: 'POST',
            data: {name: name, email: email, message: message},
            success: function(response) {
                alert('Message sent successfully!');
                $('#contactForm')[0].reset(); // Reset form
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error(textStatus, errorThrown);
                alert('An error occurred. Please try again.');
            }
        });
    });
});
</script>
</body>
</html>
Read Also: Ajax Multiple Image Upload Jquery PHP Example Tutorial Step 2: Process the Form Data with PHP

Create a file named formProcess.php to handle the form submission and perform server-side validation. This script will receive the form data via AJAX, validate it, and send a response back to the client.

formProcess.php
<?php
// formProcess.php

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Simple validation
if (!$name ||!$email ||!$message) {
    echo json_encode(['success' => false, 'message' => 'All fields are required.']);
} else {
    // Here you can add your logic to process the form data, e.g., send an email
    echo json_encode(['success' => true, 'message' => 'Message sent successfully']);
}
?>

This example demonstrates a basic contact form with jQuery AJAX form validation and server-side processing using PHP. The form is styled with Bootstrap, and jQuery is used to handle the form submission and validation before sending the data to the server. The server-side script (formProcess.php) receives the data, performs a simple validation, and sends a response back to the client.

Output: Ajax Validation In PHP With Jquery Example Tutorial

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#PHP
#jQuery
#MySql
#Ajax
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"