Christopher Pinski Department of Computer Science and Software Engineering



Download 40.22 Kb.
Date02.02.2017
Size40.22 Kb.
#16292
AJAX

Christopher Pinski

Department of Computer Science and Software Engineering

University of Wisconsin – Platteville

pinskic@uwplatt.edu

Abstract
Ajax is a group of technologies that when used correctly makes it easier for the programmer to communicate with a server. The group of technologies that encompass Ajax are HTML, CSS, JavaScript the Document Object Model (DOM), XML, JSON and the XMLHttpRequest. An Ajax request is formed on the client side and then sent to the server for processing. Once processed, the server usually returns information usually in XML or JSON formats. Through the use of this group of technologies programmers can update content on pages dynamically to offer the user a better experience. Ajax has made it possible for the Internet to become what it is today, a continuously updated web of information, which is at the world’s fingertips.

Introduction
In the early days of the web, pages were built statically meaning they were completely built with HTML and had no dynamic element to them. Anytime a page had to be updated it required the user to fully reload the page just to see those changes. When a reload occurs like this the whole page gets reloaded regardless of whether that data was modified or not. Static pages limited what information the creators of these pages could show their audience. Constant reloading of pages was also a burden due to the speeds of most users at the time. Most users had dial up connections that would sometimes take minutes to reload full pages of information. This meant a more efficient way of transmitting new information to the user had to be invented. Ajax was the answer to these problems but it took quite a bit of time to become used widely.

JavaScript
Today JavaScript is used almost everywhere, from the web pages on the Internet to applications on your mobile phone. It is the main technology behind Ajax that allows users on the client side to receive dynamic content from servers. JavaScript, as its name indicates, is a scripting language that is lightweight to allow use across many domains. Since JavaScript is built into all of the major web browsers it is assumed that the majority of your users can and will run the JavaScript code that you have written. Because of JavaScript’s flexibility and ease of use nearly everyone with minor programming experience can easily write code to interact with web pages. The main difficulty when using JavaScript and interacting with the DOM is that most browsers treat the DOM a little bit differently from each other. This causes issues when you receive a response from the server after an Ajax request has been made. When you go to update the data across different browsers the DOM may be different. When the DOM is different you have to do additional checking to see which browser the client is working with and make the appropriate changes.
JavaScript is not very useful when it is used on its own since you can only interact with the information the user is already presented with. This allows for things like spinning banners or rotating images but it doesn’t allow information to be updated in real time as new events occur.
Facebook and Google are good example of websites that make Ajax calls to dynamically update webpages with information stored on their servers. Both of these websites use JavaScript to make calls to their servers to retrieve new information. Once the information is received from the server they update the DOM through the use of JavaScript to present the user this information.

jQuery
JQuery was designed with the intention of making JavaScript easier to use. Specifically, it was designed to be cross browser, lightweight, traverse the DOM easier and make Ajax interactions with the server easier. Traditional JavaScript Ajax calls look like the following:
function httpRequest(id) {

if (window.XMLHttpRequest) { // code for IE7+, FF, Chrome, Opera, Safari

http=new XMLHttpRequest();

}

else { // code for IE6, IE5



http=new ActiveXObject("Microsoft.XMLHTTP”);

}

http.onreadystatechange=function() {



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

response = http.responseText;

// do something with response

}

}



dest=”servlet.php?id=” + id;

http.open("GET”, dest);

http.send();

}

Figure 1: Traditional JavaScript Ajax call [8]


This snippet of code doesn’t seem that bad when you look at it but considering this is a simple request it is only scratching the surface of how complex these requests can become. It is also a bit confusing looking at it because of the large amount of braces required for this simple request. When these requests become very complex and there are lots of different behaviors based upon the data you receive back from the server these JavaScript Ajax requests can become almost unreadable. The following is a similar request made using jQuery:
$.Ajax({

type: "POST",

url: "some.php",

data: "name=John&location=Boston",

success: function(msg){

alert( "Data Saved: " + msg );

}

});


Figure 2: jQuery Ajax call [8]
This snippet of code is much easier to read as well as understand what is happening. Someone who is not very familiar with programming can easily understand this request. With jQuery programmers can speed up development because of the amount of boilerplate work jQuery eliminates the programmer from doing.

HTML and CSS
HTML and CSS are the building blocks of our web pages. They are the elements that form the content we see and the code that JavaScript changes after responses are received from the server. The browser interprets HTML tags and then the information is displayed based upon the tags and how they are structured. CSS also known as Cascading Style Sheets are used to present the HTML in different forms. It is mostly used to make the HTML easier for the user to interpret.

JSON
JSON is a notation that is used to represent objects that are easy to parse and generate. This text format is independent of the language you are using to either parse or generate it [4]. This makes JSON a commonly used format for people creating web services that return data. Since you can easily find a parser and an encoder for just about any major language, it is convenient for developers to choose this format. In JSON an object is represented as a set of name/value pairs that take on no order [4]. An example of a JSON object can be seen below:
{"menu": {

"id": "file",

"value": "File",

"popup": {

"menuitem": [

{"value": "New", "onclick": "CreateNewDoc()"},

{"value": "Open", "onclick": "OpenDoc()"},

{"value": "Close", "onclick": "CloseDoc()"}

]

}

}}



Figure 3: JSON object [5]
Objects begin and end with curly braces. Colons follow names and a comma separates each name/value pair. When a name maps to an array of objects, the array of objects is enclosed by a square bracket [4]. This format very nicely maps to objects without the use of much overhead.

XML
XML by itself has no function. There is a common misconception that XML is designed to be an alternative to HTML, but this is not true. It was designed as a method to store data to be transported [9]. XML gives the developers the ability to create their own tags based upon what the data is. This allows for a very versatile and completely custom solution. Because of this versatility, XML is easy to parse and generate. Most of the time the developer will choose the format and names of elements that work best for them. It is also very easy to parse XML. There are many tools available for most of the major languages that will easily parse XML. Some server side tools will even generate XML for you based upon the class definitions of your objects. This XML below is the same data as the JSON above but this time in the XML format:






Figure 4: XML object [5]


In this example menu is the root element, which all XML documents must have. Under the root element you have children elements, which in this case is the popup. You can then have sub elements, which in this example are the menuitems [9]. This format provides receivers of the data with nice words that identify the data but because of the need to close tags, XML is a bit more heavy weight than other formats.

Dynamic data before AJAX
Before Ajax was invented there was a hack that involved IFrames to manipulate the DOM after data was received from the server. The first thing that the developer would have to do is hide an IFrame on the page. This is because the IFrame would be used to store data and would not be seen by the user. Using this hidden IFrame you could then make GET and POST calls to a web service. In order to make a GET call you point the source of the IFrame at the web service, and give it any parameters it requires. This would then send back some data, which could then be extracted from the hidden IFrame and injected into the DOM that the user would see [3].
Doing a POST was even more difficult for the programmer. At first they would also have to start with a hidden IFrame, but this time you would create a form within that hidden IFrame with the inputs necessary to submit the correct parameters to the web service. They could then programmatically submit the form and wait for the data to be sent back to the page. Once the data had come back to the page they could again extract it from the hidden IFrame and do as they wish with it [3].
This hack was never meant to happen in the first place and thus there were many problems with it. In Internet Explorer there were two bizarre events that would sometime be triggered by this hack. The first event was referred to as the “phantom click.” This was when the user heard a clicking sound each time a different request was sent out by the IFrame to the web service. Although this didn’t hinder performance of the call at all, it was a hindrance to the user. The other event was referred to as the “throbber of doom.” This event triggered the throbber icon to animate forever while the IFrame was loading. Again this was not a hindrance on the call to the web service at all, but rather one to the user [3].

Client Side Processing vs Server Side Processing
When creating dynamic web pages it is often the task to decide what information will be processed on the client side and which information will be processed on the server side. There is no easy answer to this question but there are a few principles that can be applied in almost all situations. One of the first things a developer needs to figure out is what kind of hardware their target uses are going to be using. If the target users are going to be mostly using high-end machines then more processing can be done client side in order to alleviate the load that the servers need to take on. Most of the time the users will be using all types of machines and hardware ranging from low-end to high-end systems. This means that the developers will want to do as much of the processing on the server as possible. This will save the user from having to wait long to see their data once it is received from the server. The cost of doing most of the processing on the server side is that the load on the server will be greater. This will increase the costs of the company hosting these servers because they will need more processing power as well as more memory to process the increased load. Currently this power as well as memory is becoming very cheap and companies like amazon offer plans with the ability to scale very well as the server loads increase. This makes it more favorable for the developers to focus on processing their data on the server rather than the client side.
Another issue is security. When all of the processing is done on the client side, it is a lot less secure than when it is all done on the server [1]. This is because hackers could easily look at the code when it is on the client side and figure out some of the implementation details of the system.
The last thing to consider is the scalability of the your application. When you plan on moving your app from platform to platform you are better off if you have most of the processing on the server side. This is because most client side code is very platform specific and not very portable. When the work is done server side all you have to worry about is making sure the platform specific code can generate the GUI correctly. All of the client side code for requesting information from the server will be similar.

XMLHttpRequest
This request is what makes the Ajax request retrieve the data from a URL. The request is an object within the JavaScript language and has been standardized by the W3C. Once the object has made the request, a response is received and then the data is extracted into the DOM.
When using the XMLHttpRequest you can either synchronously or asynchronously send the requests. Most of the time it is recommended to use asynchronous requests since you can process other data while you are waiting for a responses from the server [7]. An example of a synchronous request can be seen below:
var request = new XMLHttpRequest();

request.open('GET', 'http://www.mozilla.org/', false);

request.send(null);

 

if (request.status === 200) {

  console.log(request.responseText);

}

Figure 5: synchronous Ajax request [7]


This request is made synchronous by the third parameter on the second line to the function open. The third line will send the request and the parameter is made null because there is no body needed for a GET request. The last if statement checks to see if the status code that was returned was 200, otherwise known as an “OK” from the server.
Asynchronous requests work a bit differently than the synchronous requests. With an asynchronous request you register a callback to be executed when the response is received from the server. An example of an asynchronous call can be seen below:
var oReq = new XMLHttpRequest();

oReq.open("GET", "external" href="http://www.mozilla.org/">http://www.mozilla.org/", true);

oReq.onreadystatechange = function (oEvent) {

  if (oReq.readyState === 4) {

    if (oReq.status === 200) {

      console.log(oReq.responseText);

    } else {

      console.log("Error", oReq.statusText);

    }

  }


};

oReq.send(null);

Figure 6: asynchronous Ajax request [7]
In this example the third parameter of the open method is now set to true to indicate that it is an asynchronous request. On the third line the handler for the response is specified. This handler is registered to the requests readyState to see if the request was complete. If the request was complete and the status of the response was “OK” then it logs the received content. The last line will actually initiate the request and the parameter is null again because there is no request body needed for a GET request.

Common Ajax Problems
The first problem with Ajax requests is that the loading indicator on the browser will not be triggered with the request. This does not affect the actual request at all, but it does not aid the user at all either. When you have some data that is being loaded you would like to notify the user that something is happening. The solution to this problem is to place a similar looking loading icon near the DOM elements that are loading. This way the user knows that there is some data being loaded and their web browser has not frozen [6].
Another Ajax problem is that requests are not permitted to access domains other than the one that the request resides on. This is commonly known as cross-site scripting (XSS). The solution to XSS is to place your server in between your web application and the third party domain. Placing a server in between your web application and the third party service will add another layer to the project but it is the only recommended solution. This will allow your web application to tell your server it needs some sort of info from the third party domain. The server can then go retrieve that data and then send it back to the web application as needed. This is also completely secure since all the requests to the third party domain are made on the server [6].
macintosh hd:users:christopherpinski:downloads:proxy.jpg

Figure 7: Visualization of XSS solution for Ajax [6]



Conclusion
Ajax may not be the single reason the Internet has taken the form of which it is in today but it was a large contributor. With Ajax, users of different sites are now able to get up to the minute data continuously, which has changed the way many industries operate. People are becoming ever more reliant on minute-to-minute changes in their jobs and everyday life as the world becomes more technologically centered. Also, as more and more software is becoming web and mobile based, there needs to be a way to deliver dynamic content to the users of these applications continuously. I would also argue that most people throughout their careers would come across these technologies in one form or another because of this growth of Internet and mobile apps. This is why it is beneficial to have at least a basic understand of the technologies so that when you do have to work with them, they are familiar and easy to implement. This growth will force each particular part of Ajax to evolve and take on new shapes as the Internet continues to evolve but the basic principles of transmitting data to and from the external server will always hold with Ajax.

References


  1. Brock, A. (n.d.). demosthenes.info – The Client-Server Model. demosthenes.info – blog. Retrieved October 24, 2012, from http://demosthenes.info/blog/137/The-Client-Server-Model

  2. Empire Burlesque. (n.d.). W3Schools Online Web Tutorials. Retrieved October 24, 2012, from http://www.w3schools.com/xml/cd_catalog.xml

  3. IFrame Call. (n.d.). Main Page - Ajax Patterns. Retrieved October 23, 2012, from http://ajaxpatterns.org/archive/IFrame_Call.php

  4. JSON. (n.d.). JSON. Retrieved October 23, 2012, from http://www.json.org

  5. JSON Example. (n.d.). JSON. Retrieved October 23, 2012, from http://json.org/example.html

  6. Solutions to 5 Common Ajax Problems | Webdesigner Depot. (n.d.). Web Design Blog - Webdesigner Depot. Retrieved October 25, 2012, from http://www.webdesignerdepot.com/2009/12/solutions-to-5-common-ajax-problems/

  7. Synchronous and asynchronous requests. (n.d.). Mozilla Developer Network. Retrieved October 25, 2012, from https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

  8. The Power of jQuery with Ajax. (n.d.). Six Revisions - Web Design Articles, News, Tutorials. Retrieved October 21, 2012, from http://sixrevisions.com/javascript/the-power-of-jquery-with-ajax/

  9. XML Introduction - What is XML?. (n.d.). W3Schools Online Web Tutorials. Retrieved October 24, 2012, from http://www.w3schools.com/xml/xml_whatis.asp

Directory: ~yangq -> csse411 -> csse411-materials -> f12
csse411-materials -> Multi-Core Software Development with Examples in C++
csse411-materials -> Web Security a Programmer’s Perspective
f12 -> Emotional Annotation of Text David Gallagher
csse411-materials -> Computer Science / Software Engineering uw-platteville
csse411-materials -> Security of Mobile Devices Lon Kastenson Abstract
csse411-materials -> Developing for Android Erik Nykl Abstract
csse411-materials -> Spyware, Malware, and Viruses Anthony Bosnak Department of Computer Science & Software Engineering University of Wisconsin – Platteville
csse411-materials -> Personal Computing: Past, Present, and Future Michael Wills
csse411-materials -> Virtual Reality (VR) Kyle Maitland Department of Computer Science University of Wisconsin Platteville

Download 40.22 Kb.

Share with your friends:




The database is protected by copyright ©ua.originaldll.com 2024
send message

    Main page