Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Ajax, Effects And Validation using jQuery

In this article we will discuss about Ajax, effects and validation in jQuery.

Most important features that are recognized by JQuery are Ajax support, Widgets, UIs and Effects.

In this article we will see from life examples how to use all those interesting features.

Ajax Using JQuery

Ajax stands for Asynchronous JavaScript and XML.

As a technology, Ajax is considered the junction between client and server, as it load data from client to the back-ended server and return with the result in form of response.

Response can be string or even JSON object.

JQuery provided portable way to deal with Ajax which shortened the code written and enabled bugs to be detected in easy way.

The general form of ajax call in jquery looks like :

   [selector].load( URL, [data], [callback] );

Where the data is the data to be sent to the server and URL is the url of the server.

In Struts, for example, we provide action name only, no full path.

Ajax can be written also like that using Jquery:

Listing 1: General Syntax

$.ajax({
    type: "GET", //sending methods
    url: "URL",   // url of the server
    data: "data=" + id, //data that need to be sent to the server
       success: function(data, textStatus, XMLHttpRequest) {
       //in case of success data will contain the response
       // just append data to any element on the page using html() method    
            $("#" + counts).html(data);
     
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
           // in case of error
            alert(textStatus);
        }
});

Consider the following code:

Listing 2: Simple example

 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Tutorial - MrBool</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
        <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
        <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
        <script type="text/javascript">
                    $(document).ready(function() {
                $("#loadpage").click(function(event) {
                    $('#stage').load('result.html');
                });
            });
        </script>
    </head>
    <body>
        <p>Click on the button to load result.html file:</p>
        <div id="stage">
            STAGE
        </div>
        <input type="button" id="loadpage" value="Load Page" />
    </body>
</html>

The following is a real Example Using ajax to Traverse DOM , Auto generate row upon clicking on “Add New Record” button and on selecting certain module, the module Form related to it is loaded from database and displayed in the combobox.

Simple example

Figure 1: Simple example

The code used is very simple like that:

Listing 3: Simple call

company.onclick = function() {
    var id = this.value;
    $.ajax({
       type: "GET",
       url: "getReports", //server path “action”
       data: "data=" + id, //data sent to the server
       success: function(data, textStatus, XMLHttpRequest) {
            $("#i" + counts).html(data); //append the received data to combobox
            },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(textStatus);
        }
    });
};

What is the response is JSON String?

Since JSON string is a string with special format, so it can't be used as it is, it must be parsed to be used.

Jquery provided a method to parse the JSON string to make it available to be used.

At first the calling method should be like that:

  [selector].getJSON( URL, [data], [callback] );

And the code will be like:

Listing 4: JSON example

$.getJSON('URL from where JSON will return as response', function(jd) {
     $('#id').html('<p> Label1: ' + jd.JSONkey1 + '</p>');
     $('#id').append('<p>Label2 : ' + jd.JSONKey2+ '</p>');
              //   ...etc
});

Remember, if you are going to use load() in ajax and Jquery, and data will be passed with, you must give unique name to each in order to get read it from the request in server side.

   $("#id").load('URL', {"key1":val1+”&Key2”:val2} );

Assume you are using Java in code, then you will read the posted data as following:

 String val1=request.getParameter(“key1”);
                String val2=request.getParameter(“key2”);

Remember that request send only strings and you have to parse it yourself if you need other data types.

Effects Using Jquery:

Fancy Effects, Show , Hide, Fast, Slow, Fade in and out, Zoom, Discreet are all attractive effects provided by Jquery to enhance the look of web page.

Let's see some of those fancy effects with examples:

1- Hide/Show

Elements can be hidden on shown according to action occurrence with certain speed and timing.

Show(speed, callback) , hide(speed,callback) are functions are applied to element to perform the show/hide action, they can be parameterized with providing action speed and what happened after finishing “on callback” or can be left to default.

Listing 5: Show/Hide example

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Tutorial - MrBool</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
        <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
        <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
        <script type="text/javascript">
                    $(document).ready(function() {
                $("#show").click(function() {
                    $("img").show(2000);
                });
                $("#hide").click(function() {
                    $("img").hide(1000);
                });
            });
        </script>
    </head>
    <body>
        <img src="jquery_logo.png" />
        <br/>
        <input id="hide" type="button" value="Hide" /> <input id="show" type="button" value="Show" />

    </body>
</html>
Show/Hide example

Figure 2: Show/Hide example

2- fadeIn()/fadeOut()

Listing 6: Fade example

     <script type="text/javascript">

   $(document).ready(function() {

        $("#show").click(function() {
          $("img").fadeIn();
        });

        $("#hide").click(function() {
          $("img").fadeOut();
        });

    });
</script>

Other methods that are interesting, blind() - bounce() - fold() - shake() - scale() ...etc.

Some interesting Widgets and UI that are provided by JQuery:

1- Date Picker:

The calendar is used to specify date to reduce user tying errors, it got many formats, code is written like that:

Listing 7: Calendar

$(function() {
    $("selector").datepicker({
        changeMonth: true;
        changeYear: true;
    });
});

  
Calendar

Figure 3: Calendar

2-Accordion:

Which provide component like multisection of divs and is used to seperate data.

It’s written like that:

Listing 8: Multisection

<script type="text/javascript">
    $(function() {
        $("#accordion").accordion({
            collapsible: true;
        });
    });
</script>
Multisection example

Figure 4: Multisection example

3- pop-up dialog:

Which is a div that is written hidden inside the page and appear on button click, it contain controls and it can be modal “block the background” or non modal.

Listing 9: Pop up

<script type="text/javascript">
// specify the dialog properties, width, height, not auto open , modal or non-modal 
    $(function() {
        $("#dialogId").dialog({
            autoOpen: false,
            height: 400,
            width: 550,
            modal: true 
        }); 
//this is button action on click, open dialog
    $("#buttonId")
        .button()
        .click(function() {
            $("#dialogId").dialog( "open" );
        });
    });
</script>


Pop up

Figure 5: Pop up

Very Important note must be put in consideration, hidden object are instantly appears on page refresh and may cause inconsistent element look. So, we must ensure that it's hidden on page load using Jquery as well as following:

Listing 10: hidden on page

<style type="text/css">
    .js #elementId{display: none;}
</style>

<script type="text/javascript">
    document.documentElement.className = 'js';
</script>

JQuery Validation

Not Only UI That Jquery Care of, but also it cares of business Validation as well.

JQuery released excellent Validation Plug-ins for Form validation.

The techniques are as the following:

  • Write down your form elements and give unique id to each
  • In <script> tag define set of rules related to the elements and the messages that will appear upon validation.
  • Define validator and give it the rules and the messages and it will do the work.

Example:

Assume that we have two fields, for username and password, we want to be sure that they are entered and password length greater than or equal to 8 characters.

The scenario will go like the following:

Listing 11: Validation

<script type="text/javascript">
   var rules = {
        username: {
            required: true,
            minlength: 3,
            maxlength: 10
        },
        password: {
            required: true,
            minlength: 8             
        }

    };
        
    var messages = {
        username: {
            required: "Username is required",
            minlength: "Username Can't be less than 3 characters",
            maxlength: “Username Can't exceed limit of 10 character”       
        },

        password: {
            required: "Password is required",
            minlength: "Password Can't be less than 8 characters",
                   
        }
    };
    
    var validate = new jQueryValidatorWrapper("formId",rules, messages);
        // can be replaced by traditional button action.
        
        $("#buttonId").click(function () {
            if (!validate.validate())
                return;
            $(“#someDivId”).text(“Validation Done Successfully”);

        });

</script>

That's some of all, it worth to be the first choice for Web Designers and Developers. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login