Creating Your First Ajax Application
The heart of any Ajax-enabled web page is the XMLHttpRequest object, an object that facilitates communication with the server without posting the web page back to the web server. This communication can be done synchronously or asynchronously without postbacks. In this section, we examine how we can implement a simple application using this object. The XMLHttpRequest object is discussed at length later in this book.
Let's now take a look at how you can use this object using JavaScript with different browsers. After we get an understanding of how the XMLHttpRequest object works, we can get into the details of the Microsoft Ajax Library and its usage. This Library encapsulates all the JavaScript code in the form of an API and presents us with a set of method calls that facilitate easier development in Ajax.
You need to follow specific steps to create your first sample application using the XMLHttpRequest object. These steps are discussed in this section and the next section.
- 1. Create an instance of the XMLHttpRequest object, as shown in the following code snippet:
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
In the next section we discuss how we can implement a generic function that we can use across all common browsers. Moving ahead, we will make use of this function to create an instance of XMLHttpRequest
Creating a Generic Function for Instantiating the XMLHttpRequest Object
In this section we implement a generic function that can be used to create an instance of the XMLHttpRequest object based on the type of the browser on which it is intended to be used. This function is as follows:
<script language="javascript" type="text/javascript"> var xmlHttp = false; function getXmlHttpRequestObject() { try { //IE implementation xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { try { //Legacy implementation xmlHttp = new ActiveXObject("MsXml2.XMLHTTP"); } catch(exp) { xmlHttp = false; } } if (!xmlHttp && typeof XmlHttpRequest != 'undefined') { //Mozilla based browsers //creating a native request object xmlHttp = new XmlHttpRequest(); } } </script>
How Does It Work?
What does the previous code do? It illustrates the creation of the XMLHttpRequest object appropriate for the browser type making the request. It is done with the help of a simple exception-handling mechanism using the "try" and "catch" exception blocks. Note that this method can be called from any page in the application by simply placing this in a .js file and calling the getXmlHttpRequestObject method wherever it is required. If we place this in a .js file, we need not write the same code repeatedly in every web page.
- 2. Open Visual Studio 2005, and click File, New, Web Site to create a new web site. Name this web site and save it (see Figure 1.6).
Figure 1.6 Creating the web site
- 3. Now place the following code in the Default.aspx HTML source:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script language="javascript" type="text/javascript"> var xmlHttp = false; function getXmlHttpRequestObject() { try { //IE implementation xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { try { //Legacy implementation xmlHttp = new ActiveXObject("MsXml2.XMLHTTP"); } catch(exp) { xmlHttp = false; } } if (!xmlHttp && typeof XmlHttpRequest != 'undefined') { //Mozilla based browsers //creating a native request object xmlHttp = new XmlHttpRequest(); } } </script> <head runat="server"> <title>Creating your first ASP.NET Ajax Application</title> </head> <body> <form id="form1" runat="server"> <div> Your First AJAX application at work ! </div> </form> </body> </html>
When you execute the application, the output is similar to what is shown in Figure 1.7.
Figure 1.7 The first Ajax program
We now discuss how we can use Ajax to fetch data from the server asynchronously and display it in the client browser.
4. We have the JavaScript function in place. Now let's call and instantiate it, as shown in the following code snippet:
getXmlHttpRequestObject();
Now, the instance is ready for use:
xmlHttp.open("GET", "TestFile.txt", true); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { alert(xmlHttp.responseText); } } xmlHttp.send(null);
What Does the Previous Code Do?
What does the previous code do? It uses the XMLHttpRequest object's GET/Open method to read a text file on the server and display its content at the client side in a message box using JavaScript.
Here is how the complete code inside the <Script> tag now looks like:
<script language="javascript" type="text/javascript"> var xmlHttp = false; getXmlHttpRequestObject(); xmlHttp.open("GET", "TestFile.txt", true); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { alert(xmlHttp.responseText); } } xmlHttp.send(null); function getXmlHttpRequestObject() { try { //IE implementation xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { try { //Legacy object implementation xmlHttp = new ActiveXObject("MsXml2.XMLHTTP"); } catch(exp) { xmlHttp = false; } } if (!xmlHttp && typeof XmlHttpRequest != 'undefined') { //Mozilla based browsers //creating a native request object xmlHttp = new XmlHttpRequest(); } } </script>
- 5. Add a file called TestFile.txt to your project, open it, and type some content, such as "Welcome to the world of Ajax."
- 6. Save your work and start executing your project. You'll be prompted to add the Web.Config file to your application to enable debugging.
- 7. Accept all the defaults, and click the OK button. This executes the application and opens up a browser, showing the contents of the text file retrieved from the server on an alert in your web page. We are done!
The output is captured, as shown in Figure 1.8.
Figure 1.8 Welcome to the world of Ajax.
In the code snippet shown earlier, the open method was used to communicate with the server, and "readyState" returned a status code of 4, which implies that a transaction completed successfully.
So, after reading this section, you now should have a basic idea of how Ajax can be put in action.