Section 16.3. Pure JavaScript


16.3. Pure JavaScript

To conclude this chapter, it should also be mentioned that you do not even need Ajax to create Ajax-like effects. Or, to be more technically accurate, you do not need XMLHttpRequest to exchange data with the server. Using a bit of HTML knowledge and adding a bit of JavaScript to the mix, you can avoid the complexity of the various frameworks and just rely on your scripting knowledge.

The idea is to use a hidden frame to load another file in the browser, but in a way that the user does not see it. This new file contains JavaScript code that is created on the server and can therefore access server-side information. This code then changes some elements on the original page. This asynchronous approach has been quite common for several years, but without a fancy name like Ajax. This method avoids some of the browser incompatibility problems that made it so painful to create browser-agnostic web sites.

Figure 16-5 shows the concept: the code is loaded in either a hidden frame (<frame> element) or in an invisible iframe (<iframe> element). The latter option is preferable, because iframes can be embedded into a page. Then, the code in the iframe can change other HTML elements on the page.

Figure 16-5. Emulating Ajax without XMLHttpRequest


First of all, an invisible iframe is required:

 <iframe name="calculator" style="display: none;"></iframe> 

As you can see, the iframe is called "calcluator", hinting at the example to be usedonce again, we'll use the division example. We need the two input fields, the output field, and a button to launch the calculation:

 <form  runat="server">   <div>     <nobr>       <input type="text"  name="a" size="2" />       :       <input type="text"  name="b" size="2" />       = <span  style="width: 50px;" />     </nobr>     <br />     <input type="button" value="Divide Numbers" onclick="divideNumbers(this.form);" />   </div> </form> 

When the button is clicked, the server code that performs the calculation is loaded into the iframe. Since the iframe is not visible, this happens in the background, without the user's knowledge, and no page refresh is required.

The attribute of the iframe that holds the URL of its content is called src. Using this information, the JavaScript function is easy to write:

 <script language="JavaScript" type="text/javascript"> function divideNumbers(f) {   var a = f.elements["a"].value;   var b = f.elements["b"].value;   document.getElementById("calculator").src =     "PureJavaScript.aspx?a=" + a + "&b=" + b; } </script> 

As you can see, the URL to be loaded is PureJavaScript.aspx?a=<value>&b=<value>. Both the server code and the client script reside in the same pagethat's the same approach we used in Chapter 3. Client script reads the input data and constructs a URL with the values to calculate. The src attribute of the invisible <iframe> element is set to this URL, which loads the target page. The target page is an ASP.NET server page that can accept the parameters and perform the calculation. After calculating the answer, the ASP.NET page generates some client script that can set an HTML element on the host page to the results. This code to set the HTML element to the result will look similar to this:

 top.document.getElementById("c").innerHTML = "<result>"; 

Here's the server code that does the trick:

 <script runat="server">   protected void Page_Load(object sender, EventArgs e)   {     if (Request.QueryString["a"] != null &&         Request.QueryString["b"] != null)     {       int a = Convert.ToInt32(Request.QueryString["a"]);       int b = Convert.ToInt32(Request.QueryString["b"]);       float c = (float)a / b;       Response.Write("<script language=\"JavaScript\" type=\"text/javascript\">" +                  "top.document.getElementById(\"c\").innerHTML = \"" + c + "\";" +                  "</sc" + "ript>");       Response.End();     }   } </script> 

This code uses some useful tricks to avoid problems or even compilation errors.

  1. The </script> element is split into two parts ("</sc" + "ript>"). Otherwise, the ASP.NET parser would regard </script> as the end of the server script block, even though it is part of a string literal.

  2. The result of the division is treated as a string value when assigning it to the <span> element's innerHTML property, rather than converting it to a decimal value. Otherwise, this script could create problems on a localized ASP.NET installation. Instead of a decimal point, some languages use a decimal comma, but JavaScript only understands the decimal point.

  3. Response.End() ends the script output immediately, since we are interested only in the JavaScript code, not the rest of the page.


Example 16-6 shows the complete code: HTML, JavaScript, and a bit of CSSbut no external frameworks and no XMLHttpRequest to be seen.

This page must be named PureJavaScript.aspx for the example to work.


Example 16-6. An Ajax-like effect without XMLHttpRequest

 PureJavaScript.aspx <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">   protected void Page_Load(object sender, EventArgs e)   {     if (Request.QueryString["a"] != null &&         Request.QueryString["b"] != null)     {       int a = Convert.ToInt32(Request.QueryString["a"]);       int b = Convert.ToInt32(Request.QueryString["b"]);       float c = (float)a / b;       Response.Write("<script language=\"JavaScript\" type=\"text/javascript\">" +                      "top.document.getElementById(\"c\").innerHTML = \"" + c + "\";" +                      "</sc" + "ript>");       Response.End();     }   } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">   <title>Ajax</title>   <script language="JavaScript" type="text/javascript">   function divideNumbers(f) {     var a = f.elements["a"].value;     var b = f.elements["b"].value;     document.getElementById("calculator").src =       "PureJavaScript.aspx?a=" + a + "&b=" + b;   }   </script> </head> <body>   <form  runat="server">     <div>       <nobr>         <input type="text"  name="a" size="2" />         :         <input type="text"  name="b" size="2" />         = <span  style="width: 50px;" />       </nobr>       <br />       <input type="button" value="Divide Numbers" onclick="divideNumbers(this .form);" />     </div>   </form>   <iframe  style="display: none;"></iframe> </body> </html> 

Figure 16-6 shows the result of loading Example 16-6, entering two numbers, and clicking the Divide Number button.

Figure 16-6. The division comes from the server, but without the XMLHttpRequest object


You can use more advanced JavaScript and DOM techniques to even avoid the <iframe> HTML element. Using the DOM methods, you could dynamically create an <iframe> element, fill it with code, and later remove it again from the DOM tree. Actually, the client callback mechanism of ASP.NET 2.0 (see the section "Client Callbacks" earlier in this chapter) uses a technique like this.


So even if you cannot use Atlas right now, there are other options to enrich your web applications with Ajax effects. Always remember, however, that about 10% of users (depending on which survey you are reading, of course) have JavaScript deactivated in their browsers (see for instance http://www.w3schools.com/browsers/browsers_stats.asp), either due to company policies or because of worries about security vulnerabilities that continue to hit all relevant browsers.

Commercial Components for Ajax

Riding the Ajax wave, vendors of commercial ASP.NET controls are using XMLHttpRequest in their software. For instance, ComponentArt (http://www.componentart.com) has created the Web.UI Callback Control, which supports a much richer Client Callback mechanism than ASP.NET 2.0 alone. Infragistics NetAdvantage suite (http://www.infragistics.com) includes a data grid control called WebGrid with Ajax support to allow updates in the grid without page refreshes. Other vendors have similar solutions to offer, and new ones seem to come up faster than you can keep track of them.





Programming Atlas
Programming Atlas
ISBN: 0596526725
EAN: 2147483647
Year: 2006
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net