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.




What is Ajax and how does it work

In this post I want to give a brief explain on what is Ajax and how it works.

What is AJAX 


AJAX stands for Asynchronous JavaScript and XML. What this means, is that you can update a part of a web page without reloading the whole page. Hence, you are updating a single part of a web page asynchronously by exchanging small amounts of data with the server behind the scenes.  


How does Ajax Work?

When a user requests a page, the server will send the full HTML and CSS code at once. After the user enters his/her details in a form and submits it, the server processes the information and rebuilds the page. It then sends the full page back to the client. And so on.

When using AJAX, the page is loaded entirely only once, the first time it is requested. Besides the HTML and CSS code that make up the page, some JavaScript files are also downloaded: the AJAX engine. All requests for data to the sever will then be sent as JavaScript calls to this engine. The AJAX engine then requests information from the web server asynchronously. Thus, only small page bits are requested and sent to the browser, as they are needed by the user. The engine then displays the information without reloading the entire page. This leads to a much more responsive interface, because only the necessary information is passed between the client and server, not the whole page. This produces the feeling that information is displayed immediately, which brings web applications closer to their desktop relatives.

To demonstrate the communication between the client (browser) and the remote server, as well as the differences between the classic and the AJAX-powered applications, take a look at the diagram below:


At the heart of the AJAX method of communicating with the server lays the AJAX engine. This is nothing more than some JavaScript code that instantiates and uses the XMLHttpRequest object. This is a JavaScript object that allows sending, receiving and processing HTTP requests to and from the server without refreshing the entire page.

In AJAX-powered applications, HTTP requests for data can be made completely in the background, without the user experiencing any interruptions. This means the user can continue working and using the application, while the necessary page sections are received from the server. The XMLHttpRequest object was implemented as an ActiveX object in Internet Explorer, and has later become a native JavaScript object in most modern browsers (FireFox, Safari).

Although adding an extra layer to any kind of model should add to the response time, this is an exception. Through the use of this new layer – the AJAX engine – response time shortens and the user interface seems much more connected to the application logic. Moreover, the user no longer has to wait around for the page to load.

For further reading you can visit the following links:
Stackoverflow
Exforsys
Interaktonline