Wednesday 10 August 2011

How to do an Ajax post with client side validation using JQuery

In this post I want to explain how to do an Ajax post with client side validation using JQuery. The idea here is to have an object that can validate itself and once it is valid the data is sent through to the server.

JQuery Syntax for Ajax Post

The syntax for doing an Ajax post is fairly easy to understand and it is as follows:

$.post(url,data,success,dataType)
  • The url is the URL to which the request is sent.
  • Data is the information that is sent to the server with the request.
  • Success is a callback function that is executed if the request succeeds.
  • DataType is the type of data expected from the server and it can be either xml, json, script or html.
For more information you can read this article.

Issue to be resolved


Now assuming that you want to register a person and you only have three fields, Name; SecondName and Surname. And that the only required fields are Name and Surname. The expected outcome is as follows:

If not valid:












If valid:














Html:

<div id="result">

</div>
<form id="frmAdd" class="frmAdd" action="">
    <div>
    <label id="lblName">Name</label><br />
    <input type="text" id="Name" class="data required" /></div>
    <div>
    <label id="lblSecondName">SecondName</label><br />
    <input type="text" id="SecondName" class="data" /></div>
    <div>
    <label id="lblSurname">Surname</label><br />
    <input type="text" id="Surname" class="data required" /></div>
    <input type="button" id="btnAddPerson" value="Add Person" />
</form>

Now take note that for the inputs, i have two classes, data and required. Data is to get the data that needs to be sent through and required is to mark the fields that need to be filled in.

Data object


The first part of my data object is the data itself that is going to be sent through and its properties. Take note that the names of the properties are identical to the input fields id that have class data.


        var myObject = {

            // data to be sent
            data: {
                Name: "",
                SecondName: "",
                Surname: ""
            },

The second part of the object is to reset if there were any errors that were flagged


            // removes any errors
            reset: function () {
                $(".error").remove();
            },



The third part is to assign the data's properties with values from the input fields will the class data.


            assign: function ($element) {
                //get the element id
                var id = $element.attr("id");
                // match the property with the element
                for (var prop in myObject.data) {
                    if (myObject.data.hasOwnProperty(prop) && prop === id) {
                        // get the value and assign it to the property
                        myObject.data[prop] = $element.val();
                        return false;
                    }
                }
            },


The last part is the validation. Take note that the first call is to reset, that is, remove any errors that were flagged so that if there errors persist they can be shown else there are no errors to flag.



            valid: function () {

                myObject.reset();

                var valid = true;
                // validate
                if ($("input.required").length) {
                    $(".required").each(function (index, obj) {
                        if ($(this).val() === "") {
                            $(this).parent().append("<span style='color:red;' class='error'>This is a required field</span>");
                            valid = false;
                        }
                    });
                }
                // assign
                if ($("input.data").length) {
                    $(".data").each(function (index, obj) {
                        myObject.assign($(this));
                    });
                }
                return valid;
            }
        };

Now the last part is the event itself when a user clicks the button AddPerson.


        $("#btnAddPerson").click(function (e) {
            e.preventDefault();
            if (myObject.valid()) {
                $.post(
                    "ajax-calls.aspx", url
                    myObject.data, data
                     function (data) { success                    
                         if (data.success) {
                             $("#result").append("<span style='color:green;' class='error'>Person added successfully</span>");
                         } else {
                             $("#result").append("<span style='color:red;' class='error'>Person wasn't added successfully</span>");
                         }
                     },'json' dataType
                     );
            };
        });

Take note that i have highlighted the parts that makes up the syntax used to do an Ajax post, that we discussed in the first part of this article, in red. Therefore, before we do the Ajax post, the data must be valid first and if it is valid then the data is sent through.

One thing that i like about this method is that, if for instance the username or password are fields that need to be added and are also required fields, all you have to do is modify the html and add the username and passwords to the data as properties and you are done. And you can also go ahead and add more functionality to validate if the data sent is of the right type on the client side.

I hope this will be useful to those who enjoy playing around with jquery. Any comments and suggestions are welcomed.




No comments:

Post a Comment