Ajax The hype n n n Ajax sometimes

  • Slides: 28
Download presentation
Ajax

Ajax

The hype n n n Ajax (sometimes capitalized as AJAX) stands for Asynchronous Java.

The hype n n n Ajax (sometimes capitalized as AJAX) stands for Asynchronous Java. Script And XML Ajax is a technique for creating “better, faster, more responsive web applications” Web applications with Ajax are supposed to replace all our traditional desktop applications These changes are so sweeping that the Ajax-enabled web is sometimes know as “Web 2. 0” Ajax also cures cancer, ends hunger, and brings about world peace

The reality n Ajax is a technique for creating “better, faster, more responsive web

The reality n Ajax is a technique for creating “better, faster, more responsive web applications” n n n GUIs are HTML forms (and you know how beautiful and flexible those are) The technology has been available for some time Nevertheless, Ajax is the “hot new thing” because: n n n But they still aren’t as responsive as desktop applications, and probably never will be Web applications are useless when you aren’t on the web Google uses it extensively, in things like Google Earth and Google Suggest It has been given a catchy name Ajax is a useful technology, and a good thing to have on your resumé

How Ajax works n n n You do something with an HTML form in

How Ajax works n n n You do something with an HTML form in your browser Java. Script on the HTML page sends an HTTP request to the server The server responds with a small amount of data, rather than a complete web page Java. Script uses this data to modify the page This is faster because less data is transmitted and because the browser has less work to do

Underlying technologies n n Java. Script HTML CSS XML n n XML is often

Underlying technologies n n Java. Script HTML CSS XML n n XML is often used for receiving data from the server Plain text can also be used, so XML is optional n HTTP n All these are open standards

Starting from the browser… n Your browser must allow Java. Script, or Ajax won’t

Starting from the browser… n Your browser must allow Java. Script, or Ajax won’t work n n n Otherwise, there’s nothing special required of the browser Your browser has some way of providing data to the server—usually from an HTML form Java. Script has to handle events from the form, create an XMLHttp. Request object, and send it (via HTTP) to the server n n Nothing special is required of the server—every server can handle HTTP requests Despite the name, the XMLHttp. Request object does not require XML

The XMLHttp. Request object n n Java. Script has to create an XMLHttp. Request

The XMLHttp. Request object n n Java. Script has to create an XMLHttp. Request object For historical reasons, there are three ways of doing this n n n For most browsers, just do var request = new XMLHttp. Request(); For some versions of Internet Explorer, do var request = new Active. XObject("Microsoft. XMLHTTP"); For other versions of Internet Explorer, do var request = new Active. XObject("Msxml 2. XMLHTTP"); Doing it incorrectly will cause an Exception The next slide shows a Java. Script function for choosing the right way to create an XMLHttp. Request object

Getting the XMLHttp. Request object var request = null; // we want this to

Getting the XMLHttp. Request object var request = null; // we want this to be global function get. XMLHttp. Request( ) { try { request = new XMLHttp. Request(); } catch(err 1) { try { request = new Active. XObject("Microsoft. XMLHTTP"); } catch(err 2) { try { request = new Active. XObject("Msxml 2. XMLHTTP"); } catch(err 3) { request = null; } } } if (request == null) alert("Error creating request object!"); }

Preparing the XMLHttp. Request object n n Once you have an XMLHttp. Request object,

Preparing the XMLHttp. Request object n n Once you have an XMLHttp. Request object, you have to prepare it with the open method request. open(method, URL, asynchronous) n The method is usually 'GET' or 'POST' n The URL is where you are sending the data n n If using a 'GET', append the data to the URL If using a 'POST', add the data in a later step If asynchronous is true, the browser does not wait for a response (this is what you usually want) request. open(method, URL) n As above, with asynchronous defaulting to true

Sending the XMLHttp. Request object n n Once the XMLHttp. Request object has been

Sending the XMLHttp. Request object n n Once the XMLHttp. Request object has been prepared, you have to send it request. send(null); n n This is the version you use with a GET request. send(content); n n This is the version you use with a POST request The content has the same syntax as the suffix to a GET request POST requests are used less frequently than GET requests For POST, you must set the content type: request. set. Request. Header('Content-Type', 'application/x-www-form-urlencoded'); request. send('var 1=' + value 1 + '&var 2=' + value 2);

The escape method n In the previous slide we constructed our parameter list to

The escape method n In the previous slide we constructed our parameter list to the server n n n This list will be appended to the URL (for a GET) However, some characters are not legal in a URL n n request. send('var 1=' + value 1 + '&var 2=' + value 2); For example, spaces should be replaced by %20 The escape method does these replacements for you n request. send('var 1=' + escape(value 1) + '&var 2=' + escape(value 2));

Putting it all together n Head: n n function get. XMLHttp. Request () {.

Putting it all together n Head: n n function get. XMLHttp. Request () {. . . } // from an earlier slide function send. Request() { get. XMLHttp. Request(); var url = some URL request. open("GET", url, true); // or POST request. onreadystatechange = handle. The. Response; request. send(null); // or send(content), if POST function handle. The. Response() { if (request. ready. State == 4) { if (request. status == 200) { var response = request. response. Text; // do something with the response string } else { alert("Error! Request status is " + request. status); } } } Body: <input value="Click Me" type="button" onclick="send. Request">

On the server side n n The server gets a completely standard HTTP request

On the server side n n The server gets a completely standard HTTP request In a servlet, this would go to a do. Get or do. Post method The response is a completely standard HTTP response, but… …Instead of returning a complete HTML page as a response, the server returns an arbitrary text string (possibly XML, possibly something else)

Getting the response n n Ajax uses asynchronous calls—you don’t wait for the response

Getting the response n n Ajax uses asynchronous calls—you don’t wait for the response Instead, you have to handle an event n request. onreadystatechange = some. Function; n n function some. Function() { if(request. ready. State == 4){ var response = request. response. Text; if (http_request. status == 200) { // Do something with the response } } } To be safe, set up the handler before you call the send function n n This is a function assignment, not a function call n Hence, there are no parentheses after the function name When the function is called, it will be called with no parameters

The magic number 4 n n n The callback function you supply is called

The magic number 4 n n n The callback function you supply is called not just once, but (usually) four times request. readystate tells you why it is being called Here are the states: n 0 -- The connection is uninitialized n n n This is the state before you make the request, so your callback function should not actually see this number 1 -- The connection has been initialized 2 -- The request has been sent, and the server is (presumably) working on it 3 -- The client is receiving the data 4 -- The data has been received and is ready for use I don’t know any reason ever to care about the other states n I guess the browser just wants you to know it’s not loafing

The magic number 200 n n A ready state of 4 tells you that

The magic number 200 n n A ready state of 4 tells you that you got a response--it doesn’t tell you whether it was a good response The http_request. status tells you what the server thought of your request n n 404 Not found is a status we are all familiar with 200 OK is the response we hope to get

Using response data n When you specify the callback function, request. onreadystatechange = some.

Using response data n When you specify the callback function, request. onreadystatechange = some. Function; n you can’t specify arguments Two solutions: n Your function can use the request object as a global variable n n This is a very bad idea if you have multiple simultaneous requests You can assign an anonymous function: request. onreadystatechange = function() { some. Function(request); } n Here the anonymous function calls your some. Function with the request object as an argument.

Displaying the response n n http_request. onreadystatechange = function() { show. Contents. Alert(http_request); };

Displaying the response n n http_request. onreadystatechange = function() { show. Contents. Alert(http_request); }; http_request. open('GET', url, true); http_request. send(null); function show. Contents. Alert(http_request) { if (http_request. ready. State == 4) { /* 4 means got the response */ if (http_request. status == 200) { alert(http_request. response. Text); } else { alert('There was a problem with the request. '); } } } From: http: //developer. mozilla. org/en/docs/AJAX: Getting_Started

The ready. State property n n The ready. State property defines the current state

The ready. State property n n The ready. State property defines the current state of the XMLHttp. Request object. Here are the possible values for the ready. State property: n n n n ready. State=0 after you have created the XMLHttp. Request object, but before you have called the open() method. ready. State=1 after you have called the open() method, but before you have called send(). ready. State=2 after you have called send(). ready. State=3 after the browser has established a communication with the server, but before the server has completed the response. ready. State=4 after the request has been completed, and the response data have been completely received from the server. Not all browsers use all states Usually you are only interested in state 4 Mostly from: http: //www. w 3 schools. com/ajax_xmlhttprequest. asp

Summary n n n Create an XMLHttp. Request object (call it request) Build a

Summary n n n Create an XMLHttp. Request object (call it request) Build a suitable URL, with ? var=value suffix request. open('GET', URL) request. onreadystatechange = handler. Method; request. send(null); function handler. Method() { if (request. ready. State == 4) { if (http_request. status == 200) { // do stuff } } }

Problem: Lost response n n n You create a request object, and append your

Problem: Lost response n n n You create a request object, and append your request information to it When the server responds, its result is also in the request object Question: What happens if, before you get a response, you use the request object to send off another request? Answer: You have overwritten the request object, so the response to the original request is lost Solution: In this situation, you will need to create and use more than one request object

Problem: Only works the first time n n n You send a request using

Problem: Only works the first time n n n You send a request using GET, and it works Something changes on the server, and you want to see the new value, so you send the same request again Nothing happens! Why not? n n Answer: The browser has cached your URL; it sees that you use it again without change, and gives you the cached response Wrong solution: Turn off browser caching n n Correct solution: Change the URL in some unimportant way n n n That doesn't work at the level of Java. Script url = url + "? dummy=" + new. Date(). get. Time(); // time is in ms The server is free to ignore this parameter Another correct solution: Use POST instead of GET

Problem: Java. Script isn’t loaded n n n You put the Java. Script in

Problem: Java. Script isn’t loaded n n n You put the Java. Script in an external. js file Some browsers ignore the external Java. Script file Solution: Put a space between the opening script tag and the closing script tag n n Not this: <script type="text/javascript" src="ajax. js"></script> But this: <script type="text/javascript" src="ajax. js"> </script>

Back to the HTML DOM n n n Once we get a response back

Back to the HTML DOM n n n Once we get a response back from the server, we probably want to update our HTML page The HTML page itself is document You can get information from the HTML page n n var price = document. get. Element. By. Id("price"). value; var all. Images = document. get. Elements. By. Tag. Name("img"); var first. Img = document. get. Elements. By. Tag. Name("img")[0]; We can use the DOM to change the HTML

Adding and removing event handlers n You can add event handlers to HTML elements

Adding and removing event handlers n You can add event handlers to HTML elements n n n <input type="Submit" value="Submit" on. Click="do. It(); " /> <img src="dave. jpg" alt="me" on. Click="send. Mail(); " /> You can also add handlers programmatically, from a Java. Script function: n n var act = document. get. Element. By. Id("act"); act. onclick = take. Action; var images = document. get. Elements. By. Tag. Name("img"); for (var i = 0; i < images. length; i++) { images[i]. onclick = expand. Image; } n n n Inside expand. Image, the particular image is in the variable this Remember: Java. Script is case sensitive, HTML isn't! You can programmatically remove event handlers n act. onclick = null

<div> and <span> again n <div>. . . </div> and <span>. . . </span>

<div> and <span> again n <div>. . . </div> and <span>. . . </span> are containers n n Like <p> for paragraph, there is a blank line before and after a <div> Like <i> for italics, <span> does not affect spacing or flow The primary use of these tags is to hold an id attribute With an id, we can manipulate page content n n n // Find thing to be replaced var main. Div = document. get. Element. By. Id("main-page"); var order. Form = document. get. Element. By. Id("target"); // Create replacement var paragraph = document. create. Element("p"); var text = document. create. Text. Node("Here is the new text. "); paragraph. append. Child(text); // Do the replacement main. Div. replace. Child(paragraph, target);

inner. HTML n inner. HTML is a non-W 3 C DOM property that gets

inner. HTML n inner. HTML is a non-W 3 C DOM property that gets or sets the text between start and end tags of an HTML element n n n When the inner. HTML property is set, the given string completely replaces the existing content of the object If the string contains HTML tags, the string is parsed and formatted as it is placed into the document Syntax: var markup = element. inner. HTML; element. inner. HTML = markup; Example: document. get. Element. By. Id(some. Id). inner. HTML = response; inner. HTML is nonstandard, unreliable, and deprecated

The End

The End