Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

jQuery Ajax Form: Asynchronous Form Submit

DZone's Guide to

jQuery Ajax Form: Asynchronous Form Submit

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

 


jQuery Ajax Form provides the facility to submit a form asynchronously. This plugin is really helpful for Asynchronous file uploading. However, in this post, I am showing only the normal field submit. You can find more about the plugin here.

In this Demo, "We will create a form and style them in bootstrap and initialize them with Jquery Ajax form plugin." The directory structure for this demo is as shown below:  



In this demo, we are submitting the form field to the same page (just for demo purposes). You can use the URL property in the Ajax form or provide the URL in the ACTION attribute in the Form DOM element.
We have created a form element with 3 input fields (name, subject, roll) and a submit button. The HTML markup used is below:

<!DOCTYPE html>
<html>
<head>
    <title>Jquery AjaxForm With Bootstrap Style</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/my-style.css">
</head>
<body>
    <form id="my-detail-form">
        <div class="panel panel-success">
            <div class="panel-heading">
                <h3 class="panel-title">Ajax Form With Bootstrap</h3>
            </div>
            <div class="panel-body">
               <div class="alert alert-warning  my-message-error">
                   <a href="#" class="alert-link">...</a>
               </div>
                <div class="alert alert-success  my-message-success">
                    <a href="#" class="alert-link">...</a>
                </div>
               <input name='name' type="text" class='form-control' placeholder="Enter Your Name">
               <input name='subject' type="text" class='form-control' placeholder="Enter Your Subject">
               <input name='roll' type="text" class='form-control' placeholder="Enter Your Roll Number">
            </div>
            <div class="panel-footer">
                <button type="submit" class="btn btn-info">SUBMIT</button>
            </div>
        </div>
    </form>
    <script src="lib/jquery-1.10.1.min.js"></script>
    <script src="lib/jquery.form.min.js"></script>
    <script src="my-form-script.js"></script>
</body>
</html>
The below script shows the initialization of the Form element with the Ajax form. It has beforeSubmit handler, which does the validation of the required field. If the required field is missing, then it displays the error message at the top. It has a success handler to indicate if the form is submitted successfully and response has arrived.

/**
 * Created by saan on 10/6/13.
 */
var TS_AJAX_FORM ={
 
    /*ERROR Message Display Element Reference*/
    MY_MESSAGE_ERR : $(".my-message-error"),
 
    /*SUCCESS Message Display Element Reference*/
    MY_MESSAGE_SUC : $(".my-message-success"),
 
    /*Shows the input message and hides it in 5 seconds*/
    showMessage:function(msg, type){
 
        var message = (type === 'ERR')? this.MY_MESSAGE_ERR : this.MY_MESSAGE_SUC,
 
            txt = $(message).find('a');
 
        $(txt).html(msg);
 
        message.fadeIn('fast',function(){
 
            message.fadeOut(5000);
        })
    },
    /*
     *Handler: success, Once the form is submitted and response
     *arrives, it will be activated.
     */
    successHandler: function(responseText, statusText, xhr, form){
 
        TS_AJAX_FORM.showMessage("Form Submitted Status("+statusText+").", "SUC");
    },
    /*
     *responseText, statusText, xhr, $form: beforeSubmit, for validation   Let, title and roll is your required field.
     *Let's show an error message if these fields are blank.
     */
    beforeSubmitHandler:function(arr, form, options){
 
        var isValid = true;
 
        $.each(arr,function(index, aField){
 
            if('name' === aField.name && aField.value === ""){
 
                TS_AJAX_FORM.showMessage("Name Can not be Empty.", "ERR");
 
                isValid = false;
 
            }else if('roll' === aField.name && aField.value === ""){
 
                TS_AJAX_FORM.showMessage("Roll Can not be Empty.", "ERR");
 
                isValid = false;
            }
        });
        return isValid;
    },
    /*Initializing Ajax Form*/
    initMyAjaxForm:function(){
 
        $("#my-detail-form").ajaxForm({
 
            beforeSubmit:this.beforeSubmitHandler,
 
            success:this.successHandler,
 
            clearForm:true
        });
    }
};
/*My Small Tutorial: Execution point*/
$(document).ready(function(){
    TS_AJAX_FORM.initMyAjaxForm()
});
The initial form will look like this upon page load:


The below screenshot shows the error message when we submitted the field without entering the roll input field. This is done using the beforeSubmit handler and returning a false when roll or name is empty:


The below screen shows the success message when the form is submitted and response has arrived. If you set 'clearForm' or 'resetForm' to true, then after successful submission, all the form fields will be cleared.



Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

Published at DZone with permission of Sandeep Patel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}