1.6. Creating a Simple Web Page with AJAX

Although this book focuses on the power of using AJAX with ASP.NET 3.5 and the AJAX capabilities this framework brings to AJAX development, it is also interesting to see how you could build a simple AJAX-enabled HTML page without the use of any of the aforementioned frameworks.

To show this in action, create an ASP.NET solution within Visual Studio 2008. The first step you can take is to build the Web service that will return a value to be loaded up through the AJAX process. The code (in C#) of the Web service is presented here in Listing 1-1.

Example 1-1. The Web service to communicate with the AJAX-enabled Web page
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    [WebMethod]
    public string HelloWorld() {
        return "Hello Ajax World!";
    }
}

This is a simple C# Web service and as you can see from the single WebMethod, it only returns a string with no required parameters on the input. The AJAX page that you create for this example works with this Web service, and calls the Web service using the HTTP-GET protocol. By default, ASP.NET disallows HTTP-GET and you have to enable this capability in the web.config file in order for this example to work. Listing 1-2 shows the additions you need to make to this file.

Example 1-2. Changing the web.config file in order to allow HTTP-GET
<system.web>
   <webServices>
      <protocols>
         <add name="HttpGet" />
      </protocols>
   </webServices>
</system.web>

Including the <add> element within the <protocols> element enables the HTTP-GET protocol so that your Web page will be able to make the AJAX calls to it. Finally, the HTML page that will make the AJAX call is represented here in Listing 1-3.

Example 1-3. The HTML page that will make the AJAX calls to the Web service
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Basic Ajax Page</title>

    <script type="text/javascript" language="javascript">
       function InitiationFunction()
       {
        var xmlHttp;

        try
        {
            // Try this for non-Microsoft browsers
            xmlHttp = new XMLHttpRequest();
        }
        catch (e)
        {
            // These are utilized for Microsoft IE browsers
            try
            {
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e)
            {
                try
                {
                    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e)
                {
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }

    xmlHttp.onreadystatechange = function()
    {
      if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
      {
        response  = xmlHttp.responseXML;
        document.forms[0].statement.value =
           response.getElementsByTagName("string")[0].firstChild.nodeValue;
      }
    }

    xmlHttp.open("GET","/BasicAjax/WebService.asmx/HelloWorld?",true);
    xmlHttp.send(null);
    }
    </script>

</head>
<body>

<form>
    <div>
        Statement from server:
        <input type="text" name="statement" />
        <br />
        <br />
        <input id="Button1" type="button" value="Button"
         onclick="InitiationFunction()" />
    </div>
    </form>
</body>
</html>

From this bit of code, you can see that the HTML page creates an instance of the XMLHttpRequest object. From there, a JavaScript function is assigned to the onreadystatechange attribute. Whenever the state of the XMLHttpRequest instance changes, the function is invoked. Since, for this example, you are interested only in changing the page after the page is actually loaded, you are able to specify when the actual function is utilized by checking the readystate attribute of the XMLHttpRequest object.

if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{

}

In this case, the readystate is checked to see if it equals a value of 4 and if the request status is equal to 200, a normal request was received. If the status attribute is equal to something other than 200, a server-side error most likely occurred. A readystate value of 4 means that the page is loaded. The possible values of the readystate attribute include 0, 1, 2, 3, and 4. A value of 0 (which is the default value) means that the object is uninitialized. A value of 1 means that the open() method was called successfully, a value of 2 means that the request was sent but that no response was yet received, a value of 3 means that the message is being received, and a value of 4 (again) means that the response is fully loaded.

The open() method called by the XMLHttpRequest object is quite simple, as it is an HTTP-GET request made to the specific URL of your service.

When you run this page and click the button found on the page, you are presented with results illustrated in Figure 1-3.

Figure 1-3. Figure 1-3

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset