Submit forms using jQuery validate and serialize

jQuery validate and serialize

We were getting a lot of requests to write a tutorial on how to submit forms using jQuery validate and serialize. Now we got some time to write this tutorial with examples.

In this tutorial, we will be using the following terms (technical terms)

  • Jquery
  • Ajax
  • Serialize
  • WordPress
  • shortcode
  • jQuery Validate
  • submitHandler

We believe you are already familiar with all the above terms. If not then it’s not the end of the world. We will try to cover some basic understanding of these terms (wherever possible)

Let’s start with what we will create in this tutorial

Create a shortcode for the form – jQuery validate and serialize

First of all, we need a form that we will submit/save using ajax. We will create the form inside a WordPress shortcode. Add the following code inside the active theme’s functions.php file

<?php
add_shortcode("dcs_custom_user_form","dcs_custom_user_form");
function dcs_custom_user_form(){
 ob_start(); ?>
 <form id="dcsForm">
  <div class="dcs_form_control">
   <input type="text" name="fname" placeholder="First Name">
  </div>
  <div class="dcs_form_control">
   <input type="text" name="lname" placeholder="Last Name">
  </div>
  <div class="dcs_form_control">
   <input type="text" name="email" placeholder="Email">
  </div>
  <div class="dcs-btn-wrapper">
   <input type="submit" name="submit" value="Submit">
  </div>
 </form>
 <?php
 return ob_get_clean();
}

Add jquery validate library – jQuery validate and serialize

Now add the following line of code to your active theme’s footer.php

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>

Add Validate script – jQuery validate and serialize

Now add the following code under the above script tag. This code is to add a validate script to different form fields. You can change the script according to your form fields.

<script type = "text/javascript">
    jQuery("#dcsForm").validate({
        errorClass: "dcs_invalid",
        validClass: "dcs_success",
        rules: {
            fname: "required",
            lname: "required",
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            fname: "First Name is required",
            lname: "Last  Name is required",
            email: {
                required: "Email is required",
                email: "Invalid Email"
            }
        },
        submitHandler: function(form) {
            var ajaxurl = '<?php echo admin_url( '
            admin - ajax.php ' ) ?>';
            var dcsForm = jQuery(form).serialize();

            jQuery.ajax({
                url: ajaxurl,
                data: {
                    "dcsForm": dcsForm,
                    "action": "dcsAjaxCallFormSubmit"
                },
                type: 'POST',
                success: function(data) {
                    alert(data);
                }
            });
        }
    }); 
</script>
Code Explanation

This JavaScript code uses the jQuery library to implement form validation and asynchronous form submission. Let’s break down the code:

  1. jQuery Validation Plugin:
    • jQuery("#dcsForm").validate({ ... });: This line initializes form validation using the jQuery Validation Plugin. It targets the form with the id “dcsForm.”
  2. Validation Rules:
    • The rules object specifies the validation rules for each form field.
      • “fname” and “lname” are required fields.
      • “email” must be both required and a valid email format.
  3. Error Messages:
    • The messages object provides custom error messages for each field.
      • If “fname” or “lname” is not filled, the corresponding message will be displayed.
      • For the “email” field, if it’s not filled or not a valid email, the appropriate error messages will be shown.
  4. Styling Classes:
    • errorClass: "dcs_invalid": Applied to elements with errors.
    • validClass: "dcs_success": Applied to elements that pass validation.
  5. Submit Handler:
    • submitHandler: function(form) { ... }: This function is executed when the form is successfully validated and submitted.
    • It sets the ajaxurl variable to the admin-ajax.php URL in WordPress.
    • It serializes the form data using jQuery(form).serialize() and sends it to the server using AJAX.
    • The AJAX request includes the serialized form data and an action parameter (“dcsAjaxCallFormSubmit”).
    • Upon successful completion of the AJAX request, the success callback function is executed, displaying an alert with the response data.
  6. WordPress Integration:
    • <?php echo admin_url('admin-ajax.php') ?>: This PHP code dynamically generates the URL for the admin-ajax.php file in a WordPress environment. This URL is used as the endpoint for AJAX requests.

Add ajax callback to save form data – jQuery validate and serialize

Add the following code to the active theme’s functions.php

<?php
/*--ajax function to save info--*/
add_action('wp_ajax_dcsAjaxCallFormSubmit', 'dcsAjaxCallFormSubmit');
add_action('wp_ajax_nopriv_dcsAjaxCallFormSubmit', 'dcsAjaxCallFormSubmit'); // not really needed
function dcsAjaxCallFormSubmit() {
    parse_str($_POST["dcsForm"], $_POST);
    update_user_meta(get_current_user_id(), 'first_name', $_POST['fname']);
    update_user_meta(get_current_user_id(), 'last_name', $_POST['lname']);
    update_user_meta(get_current_user_id(), 'email', $_POST['email']);
    $resp['status'] = "success";
    $resp['message'] = "data submitted";
    echo json_encode($resp);
    die();
}

Add some CSS (Optional)

Just to change the look and feel of the forms, we have added the following css. You can add this css code to your active theme’s style.css file.

.dcs_form_control {
 padding: 15px;
}

.dcs_form_control input[type="text"] {
 width: 100%;
}

.dcs-btn-wrapper {
 text-align: center;
 margin-top: 15px;
}

/*validate error css*/
label.dcs_invalid {
 color: red;
}