Stephen Kucksdorf Department of Computer Science & Software Engineering University of Wisconsin Platteville, wi 53818



Download 44.85 Kb.
Date conversion03.01.2017
Size44.85 Kb.

AJAX




Stephen Kucksdorf

Department of Computer Science & Software Engineering

University of Wisconsin - Platteville

Platteville, WI 53818

kucksdorfs@uwplatt.edu

Abstract
AJAX (Asynchronous Javascript And XML) is a relatively new framework for web browsers. AJAX is used for calling server code (PHP, ASP.net, Coldfusion, etc...) from the client using the web browser’s javascript engine. This makes the life of programmer easier when it comes to maintaining code and makes a friendlier user interface. AJAX is invoked on the client to make a call back to the server with parameters from the client. The server executes its code and returns the data from the server to the client. The data returned from the server can be returned as a string (parsable by the client) or in an XML format.

Introduction
The Internet is the largest collection of human knowledge and experiences that has ever been in existence. With a majority of the human populations “plugged in” to the Internet and the ability to publish a website easily available using hosts such as 000webhost.com, godaddy.com, and others. Then there are the people, such as Mark Zuckerberg, co-founder of the social network Facebook, who took things a step further by not only putting himself on the Internet, but allowing anyone else to have their own online Facebook profile. The beginnings of Facebook were simple, but as it grew so did the dynamic-ness of the social network. Facebook is an ideal demonstration of how AJAX technology can be utilized.

AJAX Functionality

The current version of Facebook the feed can be loaded dynamically as the user reaches the end of the page, or by clicking the “More Stories” link at the bottom of the page. If this was done without AJAX the entire page would have to be refreshed, forcing the web page back to the top of the page and causing the user to have to scroll back to the bottom of the page.

This is a great example of the power of AJAX. Asynchronous Javascript And XML (AJAX) allows for an asynchronous call to a web server. The call is made to the server using javascript, and any function calls after the call back to the server. Finally the XML portion is one of two ways to get data back from the server, the second being just a string.


Javascript: The Common Denominator
Javascript is the heart of AJAX technology. While not all browsers support the same methods or properties, all modern and widely used browsers have support for AJAX. But what is javascript really? Javascript is an interpreted programming language, and is the most used client-side language for websites. Because it is interpreted, it is cross platform and cross browser compatible. However, there are variations in the interpretations, most noticeably in the DOM (Document Object Model [4]). For instance, while the code has been lost, code to add more options to a select element was very difficult. Since that time (around 2009), Internet browsers have had updates, and thanks to W3C (World Wide Web Consortium [4]) compliance, client side programming has become easier.
Javascript by itself allows for a degree of dynamic-ness to a webpage. However, the limit to this is in the fact that javascript interacts only with data on the client’s browser. The image below is commonly used to describe the difference between an AJAX web application and a standard web application.

Figure 1: A standard Http request versus an AJAX request. [7]

The image shows how a web application interacts with the web server. In a standard application, whenever data needs to be sent to the server, the whole page “freezes” until the server responds with new data. With the AJAX engine, there is virtually no waiting period, and the page freezing does not happen.


The XMLHttpRequest Object
As previously stated, AJAX relies on the XMLHttpRequest object to perform asynchronous calls to the server. With the following javascript function, an XMLHttpRequest object is created, if it is supported by the browser.

Figure 2: Figure 2: Creations of an XMLHTTPRequest object. [1][2]


The XMLHttpRequest needs to be implemented using the embedded try-catch block because older versions of Internet Explorer (IE 6 and earlier) does not support the “Msxml2.HMLHTTP” parameter when creating a new ActiveXObject. The following properties are supported [1][2][5]:

  • readyState - the XMLHttpRequest state

    • 0 - Uninitialized

    • 1 - Loading

    • 2 - Loaded

    • 3 - Interactive (the user may use the object, but data is not fully loaded)

    • 4 - Complete

  • responseText - A string representation of the data sent back from the server.

  • responseXML - Data serialized by the server to an XML format.

  • status - The HTTP status code request (200 OK, 404 Page Not Found).

  • statusText - The HTTP status text (text representation of status).

  • timeout - Gets or sets the timeout value (in milliseconds).

With the exception of timeout, all of the properties are read-only. The following methods are supported [1][2][5]:

  • open(method, URL, async) - Starts the call back to the server (does not send data), method and URL are required, async is optional.
    • method - GET or POST, depending on how the client should handle the callback to the server.


    • URL - The URL of the location.

    • async - True of the operation should be done asynchronously, false of it should be synchronously. This parameter is optional and the default value is true.

  • send(str) - Sends the data to the server to be evaluated (different than open, open prepares the data, send actually sends the data).

    • str - The string sent to the server if sent using POST. Optional if not data needs to be sent by POST.

  • abort() - Cancels the current request to the server.

  • setRequestHeader(name, value) - Creates a valued pair that is assigned to the header being sent to the server.

    • name - The name of a valued pair.

    • value - The value of a valued pair.

  • getAllResponseHeaders() - Gets the header information from the call back to the server.

  • getResponseHeader() - Gets specific information from the header information.

And finally, the events of the XMLHttpRequest object [1][2][5]:

  • onreadystatechange - This event is raised whenever the readyState value is changed, within the function of this event there is generally a “if (readyState == 4) {...}” so that the functions associated with this event can be ran.

  • ontimeout - This event is raised whenever the timeout value exceeds the time it takes to get a response from the server. A second calling could be tried, otherwise there is generally some other kind of error handling for this event.



AJAX and Web Services

Web services are functions to allow external programs to access local data. This can be used to implement a database connection, so that the connection string for the database does not need to be stored with the client application. If the database needs some data to remain private, and that the database queries aren’t used in the individual applications. There are two major types of web services, REST and SOAP. [1]

REST stands for “REpresentational State Transfer”. REST is a stateless protocol, just like Http. This means that the World Wide Web can be seen as one big REST application. REST also uses methods that HTTP forms use (GET and POST), but also has its own (DELETE and PUT being two methods). REST sends and receives data as a string of characters (just like Http). This means that a customized way of parsing data needs to be implemented on both the server where the REST application is hosted, and all of the client applications (such as HTML in a web browser).
SOAP stands for “Simple Object Access Protocol”. SOAP, just like REST and Http, is a stateless protocol. SOAP’s protocol requires that the data being sent to and from the server to be in an XML format. This means that any serializable data can be sent over the SOAP protocol. Because the data is in an XML format the data needs to be parsed, parsing takes time; therefore, SOAP is considered slower. But because SOAP is so versatile, ASP.net web services use SOAP web services.
Because web services are web based, AJAX can be used to invoke them. Parameters are sent the same way as with a regular AJAX request. There is no difference between a regular AJAX request and an AJAX request to a web service. Parameters need to be set up the same way, headers should be changed or not changed, and the send method should always follow open.

AJAX versus Adobe Flash, Silverlight, and Java Applets

With all the complexity of AJAX, who would want to use it when there are tools that can be embedded into the HTML code of a page, and ran from the client? Just looking at the XMLHttpRequest methods, properties, and events can make experienced programmers shy away from web site applications entirely1. Web programming in all of its complexity can be very overwhelming and if not approached correctly. Web programming can cost more time and money that what most companies would want to pay. So again, why develop web sites instead of alternatives such as Adobe Flash, Silverlight, and Java Applets?

Each of those requires plug-ins to be installed on the client computer. While obtaining plug-ins isn’t overly difficult for Windows and Mac users, Linux is another story. Microsoft Silverlight isn’t completed supported across all platforms, so Novell using their Mono framework created Moonlight, which is a decent substitute for Silverlight, but has its drawbacks. The company called Netflix, where users can rent unlimited movies per month and stream movies online uses Silverlight in their web interface. But because of the differences between Moonlight and Silverlight (mostly on Digital Rights Management, DRM), Moonlight users cannot stream videos from Netflix.
So Silverlight is not exactly cross platform friendly. Why not use something like Adobe Flash or Java Applets? Again it comes down to plug-ins. Adobe flash does support Linux users, but there is a cost. There’s a major performance difference from switching from Windows to Linux. And Java Applets take time to load the first time they are loaded from a website (due to the need to load the JVM2 at the first run).
For each of these there is also a need to download the actual executing files, on top of all the HTML, javascript, and CSS data. For big applications this could take an unacceptably long time.
While a lot of disadvantages were pointed out, there are some advantages. For instance, the DRM in Silverlight, while it hurts non-Window and non-Apple users, does keep record companies happy knowing that their media isn’t being freely distributed on the Internet. However, whenever developing a web application, the programmers and managers should always weigh the advantages and disadvantages of AJAX and its competitors.

Microsoft ASP.net

If javascript is the heart of AJAX, then the server side language is the brain. While javascript remains pretty universal, the server side language will always be interpreted the same way, every time, no matter which operating system or browser is used to view the web page. First a language has to be chosen, and for simplicity, ASP.net using VB.net will be used for any future examples.

ASP.net is not to be confused with classic ASP. One of the biggest differences is the handling of events in ASP.net. In classic ASP (like in PHP) when the user clicks a submit button on the web page, the page is sent back to the server, and then a whole file has to be dedicated to using the information, rather than just a method. In ASP.net, event handlers are used, much like in desktop applications. This also means that, while there’s still the classic html tags “” there’s also the ASP.net equivalent “”. The first can only be read (easily) by the client, the second, due to the release of ASP.net 4.0, can be read by both the client and the server.
ASP.net is event driven, meaning that when a button is clicked, a click event is raised. This works perfectly for desktop applications, where the entire application is all in one place; however, in web applications, where data needs to be sent back to the server to be validated or stored, this poses an issue. When viewing the source, using a web browser, of an ASP.net application there are two input tags with the type being hidden; these two fields hold all the data the server will need to have an event. The server uses these two fields to invoke the method the button click needs to run, and returns to the client all the data that was previously entered into fields and the data has been validated or stored.

AJAX is meant to be used to help speed up application processing and not waste server resources if data is invalid. Javascript can be used to validate data on the client; however, prior to the release of ASP.net 4.0, the client would have to either guess at what ASP.net would generate for a unique identifier, or use some methods of classic ASP in order to do any client validation. For example, using the previous text boxes, prior to ASP.net 4.0 the code on the server (.aspx file) would have to look like this:

Figure 3: The top line demonstrates using javascript with ASP.net 3.5 and the second is ASP.net 4.0


Note that the second doesn’t have the ASP tags (<%…%>). When writing code on the page the second is easier to write and read when programming. Everything within the ASP tags are interpreted and the “Response.Write(…)” actually writes the string to the client’s source code.

ASP.net and AJAX
Since ASP.net uses its own methods of sending data to and from the server (as previously stated), it makes sense that making an AJAX implementation is different than that of a PHP project (where the programmer needs to write all of the client and server). Because very specific requirements need to be met for an ASP.net application to work properly a new control is created, the Script Manager. Through the Script Manager the client browser is able to interact with the web server asynchronously and with events. So when a button is clicked on the client, a server postback should be invoked asynchronously. However, this is not enough within the context of a regular ASP.net button, even with a Script Manager control on the application page (one needs to be on every page where AJAX calls are performed). There also needs to be a container of what should be changed. HTML by itself is made up of containers, but a specific type of container should be used when an area should be changed using these tools. The name of the tool needed here is called the Update Panel.
The Update Panel, by default, updates all ASP.net items that are within the panel. Updates are done whenever an item within the Update Panel invokes a postback (button click for example). Then all items are updated as they are changed on the server. Items within the update panel are also updated when a full page postback is performed.

ASP.net can also be used to create SOAP based web services. Special code needs to be implemented within the Script Manager to allow javascript to “see” (Visual Studios Intellisense) the ASP.net web service. The web service class and methods also needs special code in order to be seen by the clients javascript. When using a web service the programmer can write the server side code that can return data from the server to the client. One of the biggest advantages of this is any data that is serializable to XML can be sent back to the client’s javascript code. So if I have an array of integers being sent back from the server, the javascript will create its own array and populate the array with the data.

Using web services with ASP.net and AJAX allows the programmer to have more control over both the client and the server. Since the client can call specific methods the programmer can have specific methods needed to update the web page dynamically. If the programmer does not like to use javascript to validate data, this is a good way to have data be validated live without having to rely on the default ASP.net AJAX partial page updates.

The AJAX Control Toolkit
Microsoft started development on the AJAX Control Toolkit (now maintained by CodePlex.com [6]). CodePlex maintains several tools that are useful when developing asp.net applications. These are premade tools which, when used correctly, allow developers to spend less time on data validation and submission using javascript, and more time developing using either VB.net or C#.net (either of these languages can be used interchangeably when developing ASP.net applications). Some of the tools that can be used include:


  • Calendar extender- Creates a calendar when a text box is clicked (or associated button) and can fill in the date by clicking on a date.

  • Mutually Exclusive Checkbox - Allows checkboxes to automatically become unchecked when another box becomes checked.

    • These basically make checkboxes similar to radio buttons.

  • Always Visible Control - Allows a section of the web page to always be visible in different parts of the web page.

  • Confirm Button - Shows a confirm window double checking that the user wants to submit the webpage.

    • If the user clicks “OK” or “Yes” then a postback occurs, otherwise a postback does not occur.
  • HTML Editor - Allows the end user to input rich formatted text into a textbox. While this is a great tool for up and coming web designers, it is recommended to not use on a public server without AntiXSS Sanitizer Provider (cross site scripting).


There are more tools, but these show a wide array of things that can be done to lighten the load on web developers3.

Conclusion
AJAX is a wonderful technology. However, with items like Adobe Flash or Microsoft Silverlight (Novell Moonlight), many programmers choose these options because they are easier to program with. While they allow for a similar-to-desktop experience, they also take longer to load than AJAX applications. Microsoft has made AJAX applications easier, by not only writing javascript libraries that are automatically imported, but that also keeps the event handling on the server working. Now programming is even easier with CodePlex’s AJAX Control Toolkit, a library free to download, which currently contains forty-three tools. Each of these tools contains the cross browser javascript, so the programmer does not have to spend a majority of their time writing client side code (several times over to be cross browser compatible).
The web is a complicated and relatively new frontier for programmers to write code for. Now we not only should know our main server side language, but we also should know javascript for the major browsers. If a programmer can handle that, then web applications are sure to continue and become more interesting.
References:


  1. Ballard, Phil. Sams teach yourself Ajax, JavaScript, and PHP all in one. Indianapolis, Ind: Sams Pub, 2009.

  2. Negrino, Tom. JavaScript and Ajax for the Web. Berkeley, CA: Peachpit Press, 2009.

  3. "Ajax (programming)." Wikipedia, the Free Encyclopedia. Web. .

  4. "AJAX Tutorial." W3Schools Online Web Tutorials. Web. .

  5. "XMLHttpRequest Object." MSDN. Web. .


  6. "Ajax Control Toolkit Tutorials - ASP.NET Ajax Library." Home: The Official Microsoft ASP.NET Site. Web. .

  7. "How AJAX Applications Benefit Your Web Server." BounceWeb Web Hosting Blog. Web. .

1This was noted at my first internship at Computer Systems LLC.

2http://stackoverflow.com/questions/4268241/speeding-up-the-load-time-of-a-java-applet-in-a-browser-control

3 For a full list of tools, as well as the most up to date version of the toolkit please visit - http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Default.aspx





The database is protected by copyright ©hestories.info 2017
send message

    Main page