Making AJAX Calls using jQuery

Exclusive offer: get 50% off this eBook here
ASP.NET jQuery Cookbook

ASP.NET jQuery Cookbook — Save 50%

Over 60 practical recipes for integrating jQuery with ASP.NET

$26.99    $13.50
by Sonal Aneel Allana | April 2011 | .NET

This article demonstrates the making of AJAX calls using jQuery. It describes three basic techniques of sending AJAX request to the server: via page methods, web services, and HTTP handlers. It also demonstrates the use of the Firebug add-on in Mozilla Firefox browser to investigate the AJAX request/response.

In this article by Sonal Aneel Allana, author of ASP.NET jQuery Cookbook, we will cover:

  • Setting up AJAX with ASP.NET using jQuery
  • Using Firebug to view AJAX request/response
  • Consuming page methods with AJAX
  • Consuming web services with AJAX

 

ASP.NET jQuery Cookbook

ASP.NET jQuery Cookbook

Over 70 practical recipes for integrating jQuery with ASP.NET

        Read more about this book      

(For more resources on ASP.NET, see here.)

Introduction

AJAX (Asynchronous JavaScript and XML), a term coined by Jesse James Garrett of Adaptive Path, stands for a combination of different technologies that help to communicate seamlessly with the server without the need for a page refresh. AJAX applications involve the following technologies:

  • JavaScript for running the core AJAX engine
  • XmlHttpRequest object to communicate with the server
  • Web presentation using XHTML and CSS or XSLT
  • DOM to work with the HTML structure
  • XML and JSON for data interchange

The XmlHttpRequest object is used for posting HTTP/HTTPS requests to the server. Most modern browsers have a built-in XmlHttpRequest object.
JSON (JavaScript Object Notation) is a lightweight data interchange format and is increasingly used in AJAX applications today. It is basically a collection of name/value pairs.

In classic web applications, the client submits data to the server for processing and the server sends back refreshed content to the client. This causes a visible page refresh and the web user must wait for a page reload before further interaction with the web application.

AJAX, however, eliminates the need for an explicit page refresh by communicating with the server behind the scenes. It uses the power of XmlHttpRequest object to post a request to the server. Thus, the backend communication with the server is transparent to the end user. In addition, using AJAX, only the data that is required to be updated can be selectively refreshed on the page.

ASP.NET jQuery Cookbook

The previous figure is the traditional model for web applications (left) compared to the AJAX model (right).

The previous figure shows the basic difference between traditional and AJAX-enabled applications. In traditional web applications, the client sends requests directly to the server and waits to receive the corresponding response. In AJAX-based applications, however, this is replaced by a JavaScript call to the AJAX engine instead, which sends the request asynchronously to the server. As a result, web users' interaction with the application is not interrupted and users can continue to work with the application.

The jQuery library provides many methods for working with AJAX. In this article, we will explore the use of the following methods:

  • $.ajax(settings): This is a generic low level function that helps to create any type of AJAX request. There are a number of configuration settings that can be applied using this function to customize an AJAX call. It helps to set the type of HTTP request (GET/ POST), the URL, parameters, datatype, as well as the callback functions to execute successful/unsuccessful invocation of the AJAX call.
  • $.ajaxSetup(options): This method helps to define default settings for making AJAX calls on the page. The setup is done one time and all the subsequent AJAX calls on the page are made using the default settings.

Getting started

  1. Let's start by creating a new ASP.NET website in Visual Studio and name it Chapter6.
  2. Save the jQuery library in a script folder js in the project.
  3. To enable jQuery on any web form, drag-and-drop the library to add the following to the page:
    <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="js/jquery-1.4.1.js" type="text/javascript"></script>

Now let's move on to the recipes where we will see how jQuery can be used to make AJAX calls to ASP.NET code-behind. Basically, in this article, we will explore three possible approaches of communicating with the server:

  • Using page methods
  • Using web services
  • Using HTTP Handlers

So, let's get started.

Setting up AJAX with ASP.NET using jQuery

In this recipe, we will set up our ASP.NET web page to execute an AJAX call. We will also see how to set the default AJAX properties.

Getting ready

  1. Create an HTML file Content.html in the project and add the following contents:

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <title>Content Page</title>
    <link href="css/content.css" rel="stylesheet" type="text/css"
    />
    </head>
    <body>
    <p>
    <table cellpadding="3" cellspacing="3" id="box-table-a">
    <tr><td>Title</td><td>Author</td><td>Genre</td></tr>
    <tr><td>Alchemist</td><td>Paulo Coelho</td><td>Fiction</td></tr>
    <tr><td>Heart of Darkness</td><td>Joseph Conrad</td><td>Classic</
    td></tr>
    <tr><td>David Copperfield</td><td>Charles Dickens</
    td><td>Classic</td></tr>
    <tr><td>Have a Little Faith</td><td>Mitch Albom</td><td>Fiction</
    td></tr>
    </table>
    </p>
    </body>
    </html>

  2. Add a new web form Recipe1.aspx to the current project.
  3. Add a button control to the web form to trigger the AJAX request.
    <asp:Button ID="btnSubmit" runat="server" Text="Click Here" />
  4. Thus, the ASPX markup of the web form is as follows:

    <form id="form1" runat="server">
    <div align="center">
    <fieldset style="width:400px;height:200px;">
    <div id="contentArea">
    <asp:Button ID="btnSubmit" runat="server" Text="Click Here" />
    </div>
    </fieldset>
    </div>
    </form>

  5. On page load, the form will appear as shown in the following screenshot:

    ASP.NET jQuery Cookbook

When the button is clicked, we will retrieve the contents of the HTML file using AJAX and display it on the page.

How to do it…

  1. In the document.ready() function of the jQuery script block, call the ajaxSetup() method to set the default properties of all AJAX calls on the page:
    $.ajaxSetup({
  2. Turn off the cache so that the contents are not cached by the browser:
    cache: false,
  3. Set the data type of the response. In this case, since we are going to load the contents from the HTML file, the dataType is HTML:
    dataType: "html",
  4. Define the callback function if the AJAX request fails. The callback function takes in three parameters: the XMLHttpRequest object, the error status, and an exception object:

    error: function(xhr, status, error) {
    alert('An error occurred: ' + error);
    },

  5. Define the global timeout in milliseconds:
    timeout: 30000,
  6. Set the type of HTTP request (GET/POST):
    type: "GET",
  7. Define the callback function to be called before the AJAX request is initiated. This function can be used to modify the Xml HttpRequest object:

    beforeSend: function() {
    console.log('In Ajax beforeSend function');
    },

  8. Define the function to be called when the AJAX request is completed:

    complete: function() {
    console.log('In Ajax complete function');
    }
    });

Now, having set the default properties in the previous code block, we will now invoke the actual AJAX call on clicking the button control on the form.

  1. Attach a handler for the click event of the button control:
    $("#btnSubmit").click(function(e) {
  2. Prevent default form submission:
    e.preventDefault();
  3. Initiate the AJAX call using the .ajax() method:
    $.ajax({
  4. Specify the URL to send the request to. In this case, we're sending the request to the HTML file:
    url: "Content.htm",
  5. Define the callback function for successful execution of the AJAX call:
    success: function(data) {

    The HTML response from the server is received in the data parameter in the preceding callback function.

  6. Clear the contents of the containing div area to remove the button control and append the received HTML response:

    $("#contentArea").html("").append(data);
    }
    });
    });

Thus, the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
cache: false,
dataType: "html",
error: function(xhr, status, error) {
alert('An error occurred: ' + error);
},
timeout: 30000,
type: "GET",
beforeSend: function() {
console.log('In Ajax beforeSend function');
},
complete: function() {
console.log('In Ajax complete function');
}
});

$("#btnSubmit").click(function(e) {
e.preventDefault();
$.ajax({
url: "Content.htm",
success: function(data) {
$("#contentArea").html("").append(data);
}
});
});
});
</script>

How it works…

Run the web form. Click on the button to initiate the AJAX request. You will see that the page content is updated without any visible page refresh as follows:

ASP.NET jQuery Cookbook

 

ASP.NET jQuery Cookbook Over 60 practical recipes for integrating jQuery with ASP.NET
Published: April 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on ASP.NET, see here.)

Using Firebug to view AJAX request/response

Most modern browsers provide Developer Tools for editing and debugging different types of content such as .html, .css, and JavaScript in real time.

In Internet Explorer 8 and above, the Developer Tools can be launched by pressing F12. In Chrome, you can access the same using Tools | Developer Tools or alternatively pressing Control + Shift + I.

Mozilla Firefox browser provides an add-on web development tool called Firebug. In this recipe, we will see how it can be used for XmlHttpRequest monitoring, thus enabling the logging of AJAX request/response for troubleshooting. We will demonstrate using the web form created in the Setting up AJAX with ASP.NET using jQuery recipe.

Getting ready

  1. Download and install the latest version of Firebug from http://getfirebug.com/.
  2. Run Recipe1.aspx in Mozilla Firefox browser. Launch Firebug from the Tools menu.
  3. The page displays the Firebug window as follows:

    (Move the mouse over the image to enlarge.)

Now, let's use Firebug step-by-step to trace the AJAX request/response.

How to do it…

  1. Click on the button control on the web form to initiate the AJAX request. As a result, the page will retrieve the HTML contents and display in the div area of the form.
  2. Click on the Console tab in the Firebug window. The window shows the console logging triggered by the callback functions defined in beforeSend and complete. It also displays the GET request initiated by the page as captured in the following screenshot:

    Firebug supports the following console functions:
    console.log: To log messages to the console at runtime
    console.debug: To log debug messages with a hyperlink to the calling line
    console.error: To log error messages
    console.info: To log information messages
    console.warning: To log warning messages

  3. To view the different types of console logging, update the complete callback function in ajaxSetup() method as follows:

    complete: function() {
    console.log('In Ajax complete function - Log Message');
    console.debug('In Ajax complete function - Debug Message');
    console.error('In Ajax complete function - Error Message');
    console.info('In Ajax complete function - Info Message');
    console.warn('In Ajax complete function - Warning Message');
    }

    Rerun the page. The logging will appear in the Console tab as follows:

  4. Next, click the Net tab in the Firebug window. This is the place where we can monitor the network activity triggered by the page. The traffic is segregated into various types such as HTML, CSS, JS, XHR, Images, Flash, and Media.
  5. Click the XHR sub-tab to monitor the XmlHttpRequest object. The window displays the request URL, response status, response size, and execution time. It also contains the following sub-tabs:
    • Params: Displays name/value pairs in the request.
    • Headers: Displays the request/response headers.
    • Response: Displays the AJAX response as received by the browser. The response can be either JSON, XML, HTML, text, or script.
    • Cache: Displays the cache details.
    • HTML: Displays the HTML response.

    Notice that the Params sub-tab contains a string with a _ prefix. This is the mechanism used by jQuery to control caching. For every request, jQuery generates a new string to ensure that the browser considers the request as a new one and does not cache the response.

  6. Next, click the Response sub-tab. This screen will display the AJAX response as received by the page. The format can be either JSON, XML, HTML, text, or script. In our case, the response is in HTML format as shown:

  7. Next, click on the HTML sub-tab. Firebug will display the AJAX response in HTML format as follows:

Consuming page methods with AJAX

There are two primary ways of using jQuery to communicate with ASP.NET code-behind based on events triggered on a web page:

  • using page methods
  • using web services

Page methods provide a handy way of invoking code-behind from client side script when simple server-side processing is required and when the application scope does not necessitate the calling of web services.

In this recipe, we will use AJAX to call a page method to check if the user name entered by the end user is valid.

Getting ready

  1. Add a new web form Recipe3.aspx to the current project.
  2. In the code-behind, add the following namespace to enable page methods:
    using System.Web.Services;
  3. Define an internal array object to store some UserNames in the system:
    public static string[] UserNameArray;
  4. Populate the array in the Page_Load method as follows:

    protected void Page_Load(object sender, EventArgs e)
    {
    UserNameArray = new string[7] { "testid01", "testid02",
    "testid03", "testid04", "testid05", "testid06", "testid07" };
    }

  5. Write a page method with a single input parameter sUserName. The page method will check if the input user name exists in the system and will return false if the user name is not found in the system.

    [WebMethod()]
    public static bool CheckUserName(string sUserName)
    {
    foreach (string strUsername in UserNameArray){
    if (sUserName == strUsername)
    return true;
    }

    return false;
    }

    Note that the page method is defined with a label [WebMethod()]. Also, to be able to call the method directly, we must define it as static.

  6. On the web form, add a TextBox control to enter the username. Also add a button control to trigger the AJAX request as follows:

    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtUserName" runat="server"></
    asp:TextBox>
    <asp:Button ID="btnSubmit" runat="server" Text="Check User
    Name" />
    </div>
    </form>

  7. Thus, on page load, the web form will appear as shown below:

    ASP.NET jQuery Cookbook

We will now trigger an AJAX call to the page method on clicking the button control.

 

ASP.NET jQuery Cookbook Over 60 practical recipes for integrating jQuery with ASP.NET
Published: April 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on ASP.NET, see here.)

How to do it…

  1. In the document.ready() function of the jQuery script block, define the event handler for the click event of the button control:
    $("#btnSubmit").click(function(e) {
  2. Prevent default form submission:
    e.preventDefault();
  3. Check if the TextBox is empty and alert the user:

    if ($("#txtUserName").val() == '')
    alert("Please enter the UserName");

  4. If the TextBox is not empty, call the sendData() function and pass the input data as a parameter to the function:

    else
    sendData($("#txtUserName").val());
    });

  5. Now we will define the sendData() function that takes in a single parameter i.e. sUserName):
    function sendData(sUserName) {
  6. Get the base path of the page:
    var loc = window.location.href;
    loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "Recipe3.
    aspx" : loc;
  7. Call the .ajax() method:
    $.ajax({
  8. Specify the request type as HTTP POST:
    type: "POST",
  9. Specify the complete URL of the page method to which the request needs to be sent:
    url: loc + "/CheckUserName",
  10. Pass the input parameter sUserName in .json format:
    data: '{"sUserName":"' + sUserName + '"}',

    Note that JSON serialised data consists of name/ value pairs in the format {"name1" : "value1", "name2" : "value2", "name3" : "value3"}.

  11. Specify the content type of the request/response:
    contentType: "application/json; charset=utf-8",
  12. Specify the response data type:
    dataType: "json",
  13. Define the callback function for successful invocation:

    success: function(msg) {
    if (msg.d)
    alert("The User Name is valid");
    else
    alert("The User Name is invalid")
    },

    Note that the AJAX response is wrapped in a d object, e.g. {"d":true}. Hence, to access the Boolean response from the page method, we use msg.d.

  14. Specify the callback function in case of failure:

    error: function() {
    alert("An unexpected error has occurred
    during processing.");
    }
    });
    }

Thus, the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function(e) {
e.preventDefault();
if ($("#txtUserName").val() == '')
alert("Please enter the UserName");
else
sendData($("#txtUserName").val());
});

function sendData(sUserName) {
var loc = window.location.href;
loc = (loc.substr(loc.length - 1, 1) == "/") ? loc +
"Recipe3.aspx" : loc;
$.ajax({
type: "POST",
url: loc + "/CheckUserName",
data: '{"sUserName":"' + sUserName + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d)
alert("The User Name is valid");
else
alert("The User Name is invalid")
},
error: function() {
alert("An unexpected error has occurred during processing.");
}
});
}
});
</script>

How it works…

Run the web page. Enter any random data in the TextBox and click the button control. The page sends an AJAX request to the page method. On receiving a response, it throws an error as shown below:

ASP.NET jQuery Cookbook

On entering a username that exists in the system, the page displays the following message:

ASP.NET jQuery Cookbook

There's more…

Let's inspect the AJAX request/response using Firebug. Launch Firebug in Mozilla Firefox and submit a username for verification.

The Firebug window will log the JSON request as follows:

ASP.NET jQuery Cookbook

The corresponding response received from the page method is logged in the Response subtab as shown next:

ASP.NET jQuery Cookbook

Switch to the JSON sub-tab to view the JSON deserialised response:

ASP.NET jQuery Cookbook

Consuming web services with AJAX

In addition to page methods, jQuery also enables the making of AJAX calls to web services. In this recipe, we will validate the username keyed in by the end user by making a call to a web service instead.

Getting ready

  1. Add a web service UserNameWS.asmx to the current project.
  2. Add the following namespace to the code-behind:
    using System.Web.Services;
  3. To enable the web service to be called using AJAX, add the following:
    [System.Web.Script.Services.ScriptService]
  4. Add a web method to validate the username as follows:

    [WebMethod]
    public bool CheckUserName(string sUserName)
    {
    string[] UserNameArray;
    UserNameArray = new string[7] { "testid01", "testid02",
    "testid03", "testid04", "testid05", "testid06", "testid07" };
    foreach (string strUsername in UserNameArray)
    {
    if (sUserName == strUsername)
    return true;
    }
    return false;
    }

  5. Add a new web form Recipe4.aspx to the current project.
  6. Add a TextBox and a Button control to the form as follows:

    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtUserName" runat="server"></
    asp:TextBox>
    <asp:Button ID="btnSubmit" runat="server" Text="Check User
    Name" />
    </div>
    </form>

  7. Thus, the page appears as shown:

    ASP.NET jQuery Cookbook

We will now invoke the web service using AJAX when the button is clicked.

How to do it…

  1. In the document.ready() function of the jQuery script block, define the event handler for the click event of the button control:
    $("#btnSubmit").click(function(e) {
  2. Prevent default form submission:
    e.preventDefault();
  3. Check if the TextBox is empty and alert the user:

    if ($("#txtUserName").val() == '')
    alert("Please enter the UserName");

  4. If the TextBox is not empty, call the sendData() function and pass the input data as a parameter to the function:

    else
    sendData($("#txtUserName").val());
    });

  5. Now we will define the sendData() function that takes in a single parameter i.e. sUserName):
    function sendData(sUserName) {
  6. Call the .ajax() method:
    $.ajax({
  7. Specify the request type as HTTP POST:
    type: "POST",
  8. Specify the web service and the corresponding web method to call:
    url: "UserNameWS.asmx/CheckUserName",
  9. Pass the input parameter sUserName in JSON format:
    data: '{"sUserName":"' + sUserName + '"}',

    Note that JSON serialised data consists of name/value pairs in the format {"name1" : "value1", "name2" : "value2", "name3" : "value3"}.

  10. Specify the content type of the request/response:
    contentType: "application/json; charset=utf-8",
  11. Specify the response data type:
    dataType: "json",
  12. Define the callback function for successful invocation:

    success: function(msg) {
    if (msg.d)
    alert("The User Name is valid");
    else
    alert("The User Name is invalid")
    },

    Note that the AJAX response is wrapped in a d object, e.g. {"d":true}. Hence, to access the Boolean response from the page method, we use msg.d.

  13. Specify the callback function in case of failure:

    error: function() {
    alert("An unexpected error has occurred during
    processing.");
    }
    });
    }

Thus, the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function(e) {
e.preventDefault();
if ($("#txtUserName").val() == '')
alert("Please enter the UserName");
else
sendData($("#txtUserName").val());
});
function sendData(sUserName) {
$.ajax({
type: "POST",
url: "UserNameWS.asmx/CheckUserName",
data: '{"sUserName":"' + sUserName + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d)
alert("The User Name is valid");
else
alert("The User Name is invalid")
},
error: function() {
alert("An unexpected error has occurred during
processing.");
}
});
}
});
</script>

How it works…

Run the web page. Enter any random text in the input field and click the button control. The page will make an AJAX call to the web service. On receiving the response, it displays the following message:

ASP.NET jQuery Cookbook

On keying in a username that is valid, the page displays the following:

ASP.NET jQuery Cookbook

There's more...

Let's inspect the AJAX communication using Firebug in Mozilla Firefox. Run Firebug from the Tools menu. Load the web page and click the Net tab.

Firebug logs the JSON request as shown in the following screen:

ASP.NET jQuery Cookbook

The corresponding response is captured in the Response sub-tab as follows:

ASP.NET jQuery Cookbook

On clicking the JSON sub-menu, we can view the JSON deserialised output as seen in the following screenshot:

ASP.NET jQuery Cookbook

Summary

In this article we saw the basic techniques of sending AJAX request to a server and the use of Firebug add-on to investigate the AJAX request/response.


Further resources on this subject:


About the Author :


Sonal Aneel Allana

Sonal Aneel Allana is a Senior Technical Consultant with Accentiv' SurfGold, Singapore. She has over a decade of experience in building web and desktop solutions in Microsoft technologies. She has worked with government agencies, credit bureaus, banks, financial institutions, and multinationals, delivering high-end customized solutions to meet their needs. She has worked on applications ranging from core banking software and B2B links to content management, workflow, and loyalty engines.

From time to time, she has also taken up the role of project lead and has carried numerous projects from conceptualization through implementation successfully. In addition to her experience in Microsoft technologies, she is well versed in the J2EE and LAMP platforms.

She holds a Master's degree in Computer Science from the National University of Singapore and a Bachelor's degree in Computer Engineering from Mumbai University. She is also passionate about network and data security and has a certificate in Security Technology and Management from the Institute of Systems Science, National University of Singapore.

Books From Packt


ASP.NET 4 Social Networking
ASP.NET 4 Social Networking

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

ASP.NET Site Performance Secrets
ASP.NET Site Performance Secrets

jQuery 1.4 Animation Techniques: Beginners Guide
jQuery 1.4 Animation Techniques: Beginners Guide

ASP.NET MVC 2 Cookbook
ASP.NET MVC 2 Cookbook

Spring Roo 1.1 Cookbook
Spring Roo 1.1 Cookbook

JasperReports 3.6 Development Cookbook
JasperReports 3.6 Development Cookbook

Learning jQuery 1.3
Learning jQuery 1.3


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
p
7
9
S
6
y
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software