Presentation is loading. Please wait.

Presentation is loading. Please wait.

Before we get started Tonight, an optional lab Groups? Other Questions? Tonight, an optional lab Groups? Other Questions?

Similar presentations


Presentation on theme: "Before we get started Tonight, an optional lab Groups? Other Questions? Tonight, an optional lab Groups? Other Questions?"— Presentation transcript:

1 Before we get started Tonight, an optional lab Groups? Other Questions? Tonight, an optional lab Groups? Other Questions?

2 AjaxAjax

3 XMLHttpRequest object Quick Review and More Details Quick Review and More Details

4 Using XMLHttpRequest  Create the object (in most current browsers thusly) and bind to a variable  http_request = new XMLHttpRequest();  With IE 5 and 6, use:  http_request = new ActiveXObject("Microsoft.XMLHTTP");  Create a link between the event handler and a function that handles the results  http_request.onreadystatechange = a function you define;  Create a connection and send the request  http_request.open("GET", url, true);  http_request.send(null);  Create the object (in most current browsers thusly) and bind to a variable  http_request = new XMLHttpRequest();  With IE 5 and 6, use:  http_request = new ActiveXObject("Microsoft.XMLHTTP");  Create a link between the event handler and a function that handles the results  http_request.onreadystatechange = a function you define;  Create a connection and send the request  http_request.open("GET", url, true);  http_request.send(null); Examples from: http://developer.mozilla.org/en/docs/AJAX:Getting_Started

5 Distinguishing Browsers  Since this isn't a standard, IE 5/6 and Mozilla differ in implementing XMLHttpRequest  Fortunately, you can test for this easily  Since this isn't a standard, IE 5/6 and Mozilla differ in implementing XMLHttpRequest  Fortunately, you can test for this easily if (window.XMLHttpRequest) { // Mozilla, Safari,... if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); http_request = new XMLHttpRequest(); } } else if (window.ActiveXObject) { // IE } else if (window.ActiveXObject) { // IE try { try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { } catch (e) { try { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } catch (e) {} } } example from http://developer.mozilla.org/en/docs/AJAX:Getting_Started

6 Handling Errors and Doing Something  Finally, we need to check if the request was successful, and do something based on that  Note the use of an anonymous function  Finally, we need to check if the request was successful, and do something based on that  Note the use of an anonymous function if (!http_request) { if (!http_request) { alert('Giving up :( Cannot create an XMLHTTP instance'); alert('Giving up :( Cannot create an XMLHTTP instance'); return false; return false; } http_request.onreadystatechange = function() http_request.onreadystatechange = function() { // This is the what that happens { // This is the what that happens alertContents(http_request); }; alertContents(http_request); }; http_request.open('GET', url, true); http_request.open('GET', url, true); http_request.send(null); http_request.send(null); } example from http://developer.mozilla.org/en/docs/AJAX:Getting_Started http://developer.mozilla.org/en/docs/AJAX:Getting_Started

7 The alertContents function function alertContents(http_request) { function alertContents(http_request) { if (http_request.readyState == 4) { if (http_request.readyState == 4) { if (http_request.status == 200) { if (http_request.status == 200) { alert(http_request.responseText); alert(http_request.responseText); } else { } else { alert('There was a problem with the request.'); alert('There was a problem with the request.'); } } }

8 The Trigger  Finally, a trigger to call the function <span style="cursor: pointer; text-decoration: underline" style="cursor: pointer; text-decoration: underline" onclick="makeRequest('test.html')"> onclick="makeRequest('test.html')"> Make a request Make a request</span>

9 More than one way to do this  00_ajax_demo.html is pretty complicated  Let's look at a simpler example from the jah code  Also 2 functions, but simpler  00_ajax_demo.html is pretty complicated  Let's look at a simpler example from the jah code  Also 2 functions, but simpler

10 Jah: Creating the object function jah(url,target) { if (window.XMLHttpRequest) { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); req = new XMLHttpRequest(); req.onreadystatechange = function() {jahDone(target);}; req.onreadystatechange = function() {jahDone(target);}; req.open("GET", url, true); req.open("GET", url, true); req.send(null); req.send(null); // IE/Windows ActiveX version // IE/Windows ActiveX version } else if (window.ActiveXObject) { } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); req = new ActiveXObject("Microsoft.XMLHTTP"); if (req) { if (req) { req.onreadystatechange = function() {jahDone(target);}; req.onreadystatechange = function() {jahDone(target);}; req.open("GET", url, true); req.open("GET", url, true); req.send(); req.send(); } }}

11 Jah: What's called by the listener function jahDone(target) { // only if req is "loaded" // only if req is "loaded" if (req.readyState == 4) { if (req.readyState == 4) { // only if "OK" // only if "OK" if (req.status == 200) { if (req.status == 200) { results = req.responseText; results = req.responseText; document.getElementById(target).innerHTML = results; document.getElementById(target).innerHTML = results; } else { } else { document.getElementById(target).innerHTML="jah error:\n" + document.getElementById(target).innerHTML="jah error:\n" + req.statusText; req.statusText; } }} Notice that the only thing this looks for is a state of 4 and a status of 200….

12 HTTP Status Codes  1xx are informational  2xx means success  3xx means the user agent should redirect in order to complete the transaction  4xx means a user agent error  5xx means a server error  see:http://www.w3.org/Protocols/rfc2616/rfc 2616-sec10.html http://www.w3.org/Protocols/rfc2616/rfc 2616-sec10.htmlhttp://www.w3.org/Protocols/rfc2616/rfc 2616-sec10.html  1xx are informational  2xx means success  3xx means the user agent should redirect in order to complete the transaction  4xx means a user agent error  5xx means a server error  see:http://www.w3.org/Protocols/rfc2616/rfc 2616-sec10.html http://www.w3.org/Protocols/rfc2616/rfc 2616-sec10.htmlhttp://www.w3.org/Protocols/rfc2616/rfc 2616-sec10.html

13 You can see this with telnet gilgamesh:~ hays$ telnet www.cs.unc.edu 80 Trying 152.2.131.244... Connected to www.cs.unc.edu. Escape character is '^]'. GET /indse.htm HTTP/1.0 HTTP/1.1 404 Not Found Date: Wed, 17 Sep 2008 11:41:59 GMT Server: Apache/2.2.3 (Red Hat) Content-Length: 287 Connection: close Content-Type: text/html; charset=iso-8859-1 …

14 Walking through the steps  This example shows how the status of the connection changes  Notice how a 404 is dealt with, versus how a security issue is dealt with  This example shows how the status of the connection changes  Notice how a 404 is dealt with, versus how a security issue is dealt with XMLHttpRequestWalker2.html

15 Another example  This is a simple page that calls various calculators into a div  Since I'm putting a whole web page into the div, I'm using innerHTML  To code cleanly, you'd push just a chunk of html code into the div  This is just two functions and some buttons  This is a simple page that calls various calculators into a div  Since I'm putting a whole web page into the div, I'm using innerHTML  To code cleanly, you'd push just a chunk of html code into the div  This is just two functions and some buttons aaxmlhttprequest.html

16 GotchasGotchas  This has to run through a server (the XMLHttpRequest object has no access to files)  In this version, if the text pulled in isn't XML, you get an error (but it works)  This is due to the forcing of the type of the XMLHttpRequest results  Which begs a question--do you need to use XML?  And if not XML, what?  This has to run through a server (the XMLHttpRequest object has no access to files)  In this version, if the text pulled in isn't XML, you get an error (but it works)  This is due to the forcing of the type of the XMLHttpRequest results  Which begs a question--do you need to use XML?  And if not XML, what?

17 innerHTML.htmlinnerHTML.html  All of these examples use the innerHTML property….  Did I show you this?  This shows some simple manipulations of a page using the innerHTML property outside of ajax  Note that pictures don't have any innerHTML (since there's no HTML there)  All of these examples use the innerHTML property….  Did I show you this?  This shows some simple manipulations of a page using the innerHTML property outside of ajax  Note that pictures don't have any innerHTML (since there's no HTML there)

18 form_contents1_02.htmlform_contents1_02.html  The goal of this example is show a form that uses php for validation of data  First step (well, the first successful step) was to create a simple html form for a userid  Added a function to act as a trigger  Wrote a simple php program, checkid.php, that reads a list into an array and checks for the userid there  The goal of this example is show a form that uses php for validation of data  First step (well, the first successful step) was to create a simple html form for a userid  Added a function to act as a trigger  Wrote a simple php program, checkid.php, that reads a list into an array and checks for the userid there This is inside the FormExample folder

19 The Logic  checkid.php takes a GET variable, get_id, and checks that against a text file list of ids  form_contents1_02.html has a form with a box  onchange is the trigger, calls an ajax function (trigger this with a tab, a return submits the form!)  that function passes the content to checkid.php and returns it's results to a div tag (or an alert)  thus it dynamically checks the validity without a reload  This you can do with either innerHTML or DOM references  checkid.php takes a GET variable, get_id, and checks that against a text file list of ids  form_contents1_02.html has a form with a box  onchange is the trigger, calls an ajax function (trigger this with a tab, a return submits the form!)  that function passes the content to checkid.php and returns it's results to a div tag (or an alert)  thus it dynamically checks the validity without a reload  This you can do with either innerHTML or DOM references

20 checkid.phpcheckid.php $ids=file("./files/userids.txt");$x=0; while ($ids[$x]) { $ids[$x] = trim($ids[$x]); $ids[$x] = trim($ids[$x]); $x++; $x++; } if (strlen($_GET["get_id"]) < 3 ) { echo "Userids must be 3 or more characters"; echo "Userids must be 3 or more characters"; } elseif (strlen($_GET["get_id"]) > 10 ) { echo "Userids cannot be more than 10 characters"; echo "Userids cannot be more than 10 characters"; }…else { echo "This userid is available!"; echo "This userid is available!"; }

21 The Functions  Relied on the functions from the mozilla example  The url that is called is the php script:  Relied on the functions from the mozilla example  The url that is called is the php script: function check_value(object, target_object) { makeRequest('checkid.php?get_id=' + object.value, target_object); }

22 Let the hairpulling begin…  The goal is to insert some text into the form  Easy with innerHTML, but with the DOM you have to identify the object you want to affect  We talked some about the DOM architecture, here's where things get more complicated  Recall that you can reference objects by ID, or out of an array (based on an object's position)  The goal is to insert some text into the form  Easy with innerHTML, but with the DOM you have to identify the object you want to affect  We talked some about the DOM architecture, here's where things get more complicated  Recall that you can reference objects by ID, or out of an array (based on an object's position)

23 Simple HTML  From text to DOM hierarchy  You can see this with Firefox's DOM Inspector  From text to DOM hierarchy  You can see this with Firefox's DOM Inspector from http://www.developer-x.com/content/innerhtml/ <body><div><p>Hello<em>Tim</em> How Are You? How Are You? Developer-x.com Developer-x.com </body>

24 form_contents1_03.htmlform_contents1_03.html  This version uses DOM: referencetarget_object.firstChild.nodeValue  Defined a span element with an id  Added some buttons for troubleshooting  Also, note use of: document.getElementById('is_userid_valid') (since the DOM is made of objects, not strings, you must reference the object--to display the text within an object, you have to reference the nodeValue of an object): target_object.firstChild.nodeValue = http_request.responseText;  This version uses DOM: referencetarget_object.firstChild.nodeValue  Defined a span element with an id  Added some buttons for troubleshooting  Also, note use of: document.getElementById('is_userid_valid') (since the DOM is made of objects, not strings, you must reference the object--to display the text within an object, you have to reference the nodeValue of an object): target_object.firstChild.nodeValue = http_request.responseText;

25 form_contents1_05.htmlform_contents1_05.html  Abstracted the checkid to checkvalues.php (as a general check)  Added a password input  Added another parameter, value_to_check, so that checkvalues.php would know what to check  Played with focus settings  Abstracted the checkid to checkvalues.php (as a general check)  Added a password input  Added another parameter, value_to_check, so that checkvalues.php would know what to check  Played with focus settings

26 innerHTML, DOM, what's the diff?  InnerHTML is string based, whereas the DOM manipulations are true objects  This difference means in part that code dealing with DOM objects is both slower and more verbose  DOM objects are also harder to code for in general--it's easy to change an existing object, but to make a new section you have to create the objects, then populate them  DOM objects are easier to validate  InnerHTML isn't standards compliant, and may never become part of a standard, but it's likely not going away anytime soon  InnerHTML is string based, whereas the DOM manipulations are true objects  This difference means in part that code dealing with DOM objects is both slower and more verbose  DOM objects are also harder to code for in general--it's easy to change an existing object, but to make a new section you have to create the objects, then populate them  DOM objects are easier to validate  InnerHTML isn't standards compliant, and may never become part of a standard, but it's likely not going away anytime soon

27 Suppose we want to change …  If we want to make the text of the message ajax is inserting into our form bold, we can't just add that to the javascript if we're using DOM objects as references  Can you guess why?  If we want to make the text of the message ajax is inserting into our form bold, we can't just add that to the javascript if we're using DOM objects as references  Can you guess why?

28 Here's How to Do That  This from javascript_functions2.js // Wrap the text in bold tags // Wrap the text in bold tags // First, remove the target text, right now it's in the way // First, remove the target text, right now it's in the way target_object.removeChild(target_object.firstChild); target_object.removeChild(target_object.firstChild); // Create a bold tag // Create a bold tag var b = document.createElement('B'); var b = document.createElement('B'); // Assign it an id so we can find it later // Assign it an id so we can find it later b.id="is_userid_bold"; b.id="is_userid_bold"; // Append this to the target // Append this to the target target_object.appendChild(b); target_object.appendChild(b); // Now make a text node // Now make a text node var text_insert = document.createTextNode(http_request.responseText); var text_insert = document.createTextNode(http_request.responseText); // Insert the text node into the bold node // Insert the text node into the bold node document.getElementById('is_userid_bold').appendChild(text_insert); document.getElementById('is_userid_bold').appendChild(text_insert);

29 From the Optional Lab tonight

30 Other types of data  You can also call a url that returns other formats of data: tab text, raw text, etc.  You can write a server side script to give you what you want  When we get to php we'll do some of this, but an example is php_jah.html  This file queries a php script, webconnection.php, that takes a url as a variable: http://wwwx.cs.unc.edu/~hays/INLS672/samples/aj ax/webconnection.php?target_url=www.unc.edu http://wwwx.cs.unc.edu/~hays/INLS672/samples/aj ax/webconnection.php?target_url=www.unc.edu http://wwwx.cs.unc.edu/~hays/INLS672/samples/aj ax/webconnection.php?target_url=www.unc.edu  You can also call a url that returns other formats of data: tab text, raw text, etc.  You can write a server side script to give you what you want  When we get to php we'll do some of this, but an example is php_jah.html  This file queries a php script, webconnection.php, that takes a url as a variable: http://wwwx.cs.unc.edu/~hays/INLS672/samples/aj ax/webconnection.php?target_url=www.unc.edu http://wwwx.cs.unc.edu/~hays/INLS672/samples/aj ax/webconnection.php?target_url=www.unc.edu http://wwwx.cs.unc.edu/~hays/INLS672/samples/aj ax/webconnection.php?target_url=www.unc.edu

31 php.jahphp.jah

32 Having your cake and eating too  InnerXHTML is a pair of functions written by Steve Tucker  http://www.stevetucker.co.uk/page- innerxhtml.php#release0-4 http://www.stevetucker.co.uk/page- innerxhtml.php#release0-4 http://www.stevetucker.co.uk/page- innerxhtml.php#release0-4  These functions can traverse a section of the DOM of a page, and covert the results to a string  They can also parse an html/xhtml string and produce the appropriate DOM objects  Other folks have similar tools, but this one looked particularly nice and is very simple to use  See the innerXTML folder for an example  InnerXHTML is a pair of functions written by Steve Tucker  http://www.stevetucker.co.uk/page- innerxhtml.php#release0-4 http://www.stevetucker.co.uk/page- innerxhtml.php#release0-4 http://www.stevetucker.co.uk/page- innerxhtml.php#release0-4  These functions can traverse a section of the DOM of a page, and covert the results to a string  They can also parse an html/xhtml string and produce the appropriate DOM objects  Other folks have similar tools, but this one looked particularly nice and is very simple to use  See the innerXTML folder for an example

33 Upsides to AJAX  Good way to get chunks of data into a web page  You can leverage the same code server and client side  Opens up lots of options for doing simple stuff  It is pretty cool, and that counts for something  Good way to get chunks of data into a web page  You can leverage the same code server and client side  Opens up lots of options for doing simple stuff  It is pretty cool, and that counts for something

34 Downsides to AJAX  Caching issues  Search engines  Validation  Bookmarking--since the page is changed dynamically, the url doesn't change  You can't leave the sandbox (at least not very easily)  Caching issues  Search engines  Validation  Bookmarking--since the page is changed dynamically, the url doesn't change  You can't leave the sandbox (at least not very easily)

35 Some resources  http://www.xml.com/pub/a/2005/08/19/ajax.html http://www.xml.com/pub/a/2005/08/19/ajax.html  http://www.adaptivepath.com/publications/essays/a rchives/000385.php http://www.adaptivepath.com/publications/essays/a rchives/000385.php http://www.adaptivepath.com/publications/essays/a rchives/000385.php  http://developer.mozilla.org/en/docs/AJAX:Getting_ Started http://developer.mozilla.org/en/docs/AJAX:Getting_ Started http://developer.mozilla.org/en/docs/AJAX:Getting_ Started  http://www.onlamp.com/pub/a/onlamp/2005/05/19 /xmlhttprequest.html http://www.onlamp.com/pub/a/onlamp/2005/05/19 /xmlhttprequest.html http://www.onlamp.com/pub/a/onlamp/2005/05/19 /xmlhttprequest.html  http://ajaxian.com/ http://ajaxian.com/  http://www.w3.org/TR/XMLHttpRequest/ http://www.w3.org/TR/XMLHttpRequest/  http://goog-ajaxslt.sourceforge.net/ http://goog-ajaxslt.sourceforge.net/  http://www.developer-x.com/content/innerhtml/ http://www.developer-x.com/content/innerhtml/  http://www.slayeroffice.com/articles/innerHTML_alt ernatives/ http://www.slayeroffice.com/articles/innerHTML_alt ernatives/ http://www.slayeroffice.com/articles/innerHTML_alt ernatives/  http://www- 128.ibm.com/developerworks/web/library/wa- ajaxtop1/index.html?ca=drs- http://www- 128.ibm.com/developerworks/web/library/wa- ajaxtop1/index.html?ca=drs- http://www- 128.ibm.com/developerworks/web/library/wa- ajaxtop1/index.html?ca=drs-  http://www.developer-x.com/content/innerhtml/ http://www.developer-x.com/content/innerhtml/  http://www.xml.com/pub/a/2005/08/19/ajax.html http://www.xml.com/pub/a/2005/08/19/ajax.html  http://www.adaptivepath.com/publications/essays/a rchives/000385.php http://www.adaptivepath.com/publications/essays/a rchives/000385.php http://www.adaptivepath.com/publications/essays/a rchives/000385.php  http://developer.mozilla.org/en/docs/AJAX:Getting_ Started http://developer.mozilla.org/en/docs/AJAX:Getting_ Started http://developer.mozilla.org/en/docs/AJAX:Getting_ Started  http://www.onlamp.com/pub/a/onlamp/2005/05/19 /xmlhttprequest.html http://www.onlamp.com/pub/a/onlamp/2005/05/19 /xmlhttprequest.html http://www.onlamp.com/pub/a/onlamp/2005/05/19 /xmlhttprequest.html  http://ajaxian.com/ http://ajaxian.com/  http://www.w3.org/TR/XMLHttpRequest/ http://www.w3.org/TR/XMLHttpRequest/  http://goog-ajaxslt.sourceforge.net/ http://goog-ajaxslt.sourceforge.net/  http://www.developer-x.com/content/innerhtml/ http://www.developer-x.com/content/innerhtml/  http://www.slayeroffice.com/articles/innerHTML_alt ernatives/ http://www.slayeroffice.com/articles/innerHTML_alt ernatives/ http://www.slayeroffice.com/articles/innerHTML_alt ernatives/  http://www- 128.ibm.com/developerworks/web/library/wa- ajaxtop1/index.html?ca=drs- http://www- 128.ibm.com/developerworks/web/library/wa- ajaxtop1/index.html?ca=drs- http://www- 128.ibm.com/developerworks/web/library/wa- ajaxtop1/index.html?ca=drs-  http://www.developer-x.com/content/innerhtml/ http://www.developer-x.com/content/innerhtml/


Download ppt "Before we get started Tonight, an optional lab Groups? Other Questions? Tonight, an optional lab Groups? Other Questions?"

Similar presentations


Ads by Google