7 min read

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="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 >
    <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

LEAVE A REPLY

Please enter your comment!
Please enter your name here