Ajax with jQuery

December 7, 2008 at 1:17 pm | Posted in Javascript, jQuery | 1 Comment
Tags: , , ,

jQuery has gained a lot of popularity as a Javascript framework that simplifies working with Document Object Model (DOM) and Ajax for web applications. jQuery provides a number of functions that makes dealing with Ajax easier and more powerful .

You can download jQuery framework from here, rename the downloaded file to jquery.js .

In the following example, We will take username from the user as an input, then submit this data to the server which retrieves the user details as a response.

The client page :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Demonstrating Ajax with jQuery</title>
    <script src="scripts/jquery.js" type="text/javascript" ></script>
</head>
<body>
     <form id="MyForm" >
<div id="inputDiv">
        <b> Username : </b>
        <input type="text" id="tbUsername" />
<a href="#" id="uLink">Get my info !</a></div>
<div id="outputDiv" style="display:none;"></div>
</form>
</body>
<script type="text/javascript">
    $(document).ready(function() {
        $("#uLink").click(function() {
            $.post("UserData.aspx?Func=RetrieveUserInfo",
            { username: $("#tbUsername").val() }, function(output) {
                $("#outputDiv").html(output);
                $("#outputDiv").css("display", "block");
            });
        });
    });
</script>
</html>

Our simple client page has a single HTML text input where the user enters his username then on clicking on Get My info , the username data is sent to the server and the retrieved result will be added to the outputDiv div element which is initially hidden.

let’s take a look at our code, first we have to add a reference to our jquery file which I added in a folder named scripts:

<script src="scripts/jquery.js" type="text/javascript" ></script>

Let’s now see how jQuery simplifies working with DOM and Ajax:

$(document).ready(function() {
        $("#uLink").click(function() {
            $.post("UserData.aspx?Func=RetrieveUserInfo",
            { username: $("#tbUsername").val() }, function(output) {
                $("#outputDiv").html(output);
                $("#outputDiv").css("display", "block");
            });
        });
    });

$(document).ready() is the event handler that binds a function to be executed when the document is ready to be manipulated.

$(“#uLink”).click() finds the element with id “uLink” and binds a function whenever this anchor is clicked.

$.post() is one of the jQuery functions that sends POST request to the server.

Let’s take a look on its arguments:

$.post(url,data,callback)

-url : is the url of the server page where the function sends the POST request. In our example it’s UserData.aspx?Func=RetrieveUserInfo

-data : is the data to be sent in the request in the form of key/value pairs .here we provide a single key/value pair where the key is username and its value is the value of the tbUsername input element.

-callback : is the function to executed only if the response from the server is successful .
Our callback function loads the response text to outputDiv div element and changes its display style to block to be visible.

Our UserData.aspx is quite simple,it checks the Func querystring and if it matches the RetrieveUserInfo operation, it executes the appropriate method.

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Func"] != null && Request.QueryString["Func"] != "")
        {
            if (Request.QueryString["Func"] == "RetrieveUserInfo")
            {
                RetrieveUserInfo();
            }
            Response.End();
        }
    }

    private void RetrieveUserInfo()
    {
        string UserName=Request.Params["username"];
        string userDetails = "";
        if (UserName != null && UserName != "")
        {
            if (UserName == "Mohamed.Abdelghani")
            {
                userDetails = "<B>First Name</B> : Mohamed
";
                userDetails += "<B>Last Name</B> : Abdelghani
";
                userDetails += "<B>Location</B> : Cairo
";
            }
            else
            {
                userDetails = "<B>First Name</B> : FN
";
                userDetails += "<B>Last Name</B> : LN
";
                userDetails += "<B>Location</B> :  LOC
";
            }
        }
        else
        {
            userDetails = "Please provide correct username !";
        }
        Response.Write(userDetails);
    }

The RetrieveUserInfo method is so simple and just for demonstrating the idea , in a real world scenario, it would be a query from database.

The username data sent by the $.post function is added as a parameter to the request,and is retrieved as shown :

string UserName=Request.Params["username"];

Let’s go back to our client page, Actually jQuery provides a lot of functions to simplify working with Ajax.

Another jQuery function for handling Ajax is $(“#elementID”).load(url,[data],[callback]) which loads the response data directly to the element.

Our javascript code will change to :

$(document).ready(function() {
        $("#uLink").click(function() {
            $("#outputDiv").load("UserData.aspx?Func=RetrieveUserInfo",
            { username: $("#tbUsername").val() }, function(output) {
                $(this).css("display", "block");

            });
        });
    });

The most powerful jQuery function for ajax is $.ajax() which provides more functionality like error callback that executes when the response is not successful.

Let’s take a look at our example with $.ajax() function:

$(document).ready(function() {
        $("#uLink").click(function() {
            $.ajax({
                type: "POST",
                url: "UserData.aspx?Func=RetrieveUserInfo",
                data: "username=" + $("#tbUsername").val(),
                success: function(output) {
                    $("#outputDiv").html(output);
                    $("#outputDiv").css("display", "block");
                },
                error: function()
                {
                    alert("Error");
                }
            });
        });
    });

For a full list of jQuery functions for Ajax click here.

About these ads

1 Comment »

RSS feed for comments on this post. TrackBack URI


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com. | The Pool Theme.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: