DEV Community

Cover image for Dynamic Ajax Form Validation in PHP & MySQL using jQuery
Code And Deploy
Code And Deploy

Posted on • Updated on

Dynamic Ajax Form Validation in PHP & MySQL using jQuery

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/dynamic-ajax-form-validation-in-php-mysql-using-jquery

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this post, I will show you how to create an ajax form validation in PHP & MySQL using jQuery. In my previous tutorial, I created a "Simple Dynamic Form Validation Function Using PHP" just click it to know more about the PHP function. So now I will display the error response from the server-side then show it in every form field. So here is the example result:

ajax-form-validation-in-php-mysql-using-jquery

CSS Form Validation Styles

Form validation style code using CSS. You will see this code inside assets/css/styles.css when you download the complete code.

/*Form Validation Error Styles*/
.form-group.error label,
.form-group.error .error-message {
    color:  red;
}

.form-group.error .form-control {
    border: 1px solid red;
}
Enter fullscreen mode Exit fullscreen mode

JS Form Validation Function

In this section, I will show you the actual code of my jquery/javascript function with comments so that you understand how I code it.

Before I will show you the code I will show you first the sample error JSON Array response from the server.

{
    "email":{
        "required":"Email is required."
    },
    "first_name":{
        "required":"First name is required."
    },
    "last_name":{
        "required":"Last name is required."
    },"address":{
        "required":"Address is required."
    }
}
Enter fullscreen mode Exit fullscreen mode

Then below is my complete function to process the server form validation response.

/**
 * A validation form function that will parse the json array and display to each fields
 *
 * @param {string} selector - The form selector
 * @param {json} errors - The json array response from the server form validation
 * @return {any}
 */
function validationForm(selector, errors) 
{
    // Loop the form errors
    $.each(errors, function(fieldName, fieldErrors) 
    {
        $.each(fieldErrors, function(errorType, errorValue) {

            var fieldSelector = selector + " [name='"+fieldName+"']";

            // Check if the ".form-group" class has still ".error" class
            // Then remove the ".error-message" element
            // Then rmove the ".error" class at ".form-group" class
            // To prevent element error duplication
            if($(fieldSelector).parents(".form-group").hasClass("error")) {
                $(fieldSelector).parents(".form-group").find(".error-message").remove();
                $(fieldSelector).parents(".form-group").removeClass("error");
            }

            // Insert error message after the textbox element 
            // Then add class ".error" to ".form-group" class for style needed
            $("<p class='error-message'>"+errorValue+"</p>")
                .insertAfter(fieldSelector)
                .parents(".form-group").addClass('error');

            // Remove error message on keyup by the textbox
            $(fieldSelector).on("keyup", function() {
                $(fieldSelector).parents(".form-group").find(".error-message").remove();
                $(fieldSelector).parents(".form-group").removeClass("error");
            });
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

Code Implementation

Since I already show the function now it's time to implement it in actuality. So here is the code on how to implement it.

function save() 
{
    $("#btnSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here

                response = JSON.parse(response);

                // Check if there is has_error property on json response from the server
                if(!response.hasOwnProperty('has_error')) {
                    // Reload lists of employees
                    all();

                    // We will display the result using alert
                    Swal.fire({
                      icon: 'success',
                      title: 'Success.',
                      text: response.response
                    });

                    // Reset form
                    resetForm(form);
                } else {
                    // We will display the result using alert
                    validationForm("#form", response.errors);
                }

                $this.attr('disabled', false).html($caption);

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

As you can see above code I have the save() function to store record but if the server found an error then it will not completely save it and response an error array which I parse it as JSON in client-side. As you can see in the ajax success() function I have a condition to check if the response has not JSON property "has_error" but if the "has_error" property exists then it will continue to else which we call the validatationForm() function with each parameter.

So that's pretty much it. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/dynamic-ajax-form-validation-in-php-mysql-using-jquery if you want to download this code.

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Thank you for reading. Happy Coding :)

Top comments (0)