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

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

  • View
    228

  • Download
    0

Embed Size (px)

Citation preview

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

Before we get Before we get startedstarted

Before we get Before we get startedstarted

Tonight, an optional Tonight, an optional lablab

Groups? Groups?

Other Questions?Other Questions?

Tonight, an optional Tonight, an optional lablab

Groups? Groups?

Other Questions?Other Questions?

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

AjaxAjaxAjaxAjax

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

XMLHttpRequest XMLHttpRequest objectobject

XMLHttpRequest XMLHttpRequest objectobject

Quick Review and Quick Review and

More DetailsMore DetailsQuick Review and Quick Review and

More DetailsMore Details

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

Using XMLHttpRequestUsing XMLHttpRequestUsing XMLHttpRequestUsing XMLHttpRequest

Create the object (in most current browsers Create the object (in most current browsers thusly) and bind to a variablethusly) and bind to a variable http_request = new XMLHttpRequest();http_request = new XMLHttpRequest();

With IE 5 and 6, use:With IE 5 and 6, use: http_request = new http_request = new ActiveXObject("Microsoft.XMLHTTP"); ActiveXObject("Microsoft.XMLHTTP");

Create a link between the event handler and a Create a link between the event handler and a function that handles the results function that handles the results http_request.onreadystatechange = http_request.onreadystatechange = a function you a function you definedefine;;

Create a connection and send the requestCreate a connection and send the request http_request.open("GET", url, true);http_request.open("GET", url, true); http_request.send(null);http_request.send(null);

Create the object (in most current browsers Create the object (in most current browsers thusly) and bind to a variablethusly) and bind to a variable http_request = new XMLHttpRequest();http_request = new XMLHttpRequest();

With IE 5 and 6, use:With IE 5 and 6, use: http_request = new http_request = new ActiveXObject("Microsoft.XMLHTTP"); ActiveXObject("Microsoft.XMLHTTP");

Create a link between the event handler and a Create a link between the event handler and a function that handles the results function that handles the results http_request.onreadystatechange = http_request.onreadystatechange = a function you a function you definedefine;;

Create a connection and send the requestCreate a connection and send the request http_request.open("GET", url, true);http_request.open("GET", url, true); http_request.send(null);http_request.send(null);

Examples from: http://developer.mozilla.org/en/docs/AJAX:Getting_StartedExamples from: http://developer.mozilla.org/en/docs/AJAX:Getting_Started

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

Distinguishing BrowsersDistinguishing BrowsersDistinguishing BrowsersDistinguishing Browsers

Since this isn't a standard, IE 5/6 and Since this isn't a standard, IE 5/6 and Mozilla differ in implementing Mozilla differ in implementing XMLHttpRequest XMLHttpRequest

Fortunately, you can test for this easilyFortunately, you can test for this easily

Since this isn't a standard, IE 5/6 and Since this isn't a standard, IE 5/6 and Mozilla differ in implementing Mozilla differ in implementing XMLHttpRequest XMLHttpRequest

Fortunately, you can test for this easilyFortunately, 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_Startedexample from http://developer.mozilla.org/en/docs/AJAX:Getting_Started

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

Handling Errors and Handling Errors and Doing SomethingDoing Something

Handling Errors and Handling Errors and Doing SomethingDoing Something

Finally, we need to check if the request Finally, we need to check if the request was successful, and do something based on was successful, and do something based on thatthat

Note the use of an anonymous functionNote the use of an anonymous function

Finally, we need to check if the request Finally, we need to check if the request was successful, and do something based on was successful, and do something based on thatthat

Note the use of an anonymous functionNote 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 example from http://developer.mozilla.org/en/docs/AJAX:Getting_Started

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

The alertContents The alertContents functionfunction

The alertContents The alertContents functionfunction

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.'); }} }} }}

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

The TriggerThe TriggerThe TriggerThe Trigger

Finally, a trigger to call the Finally, a trigger to call the functionfunction

Finally, a trigger to call the Finally, a trigger to call the functionfunction

<span<span style="cursor: pointer; text-decoration: underline"style="cursor: pointer; text-decoration: underline" onclick="makeRequest('test.html')">onclick="makeRequest('test.html')"> Make a requestMake a request</span></span>

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

More than one way to do More than one way to do thisthis

More than one way to do More than one way to do thisthis

00_ajax_demo.html is pretty 00_ajax_demo.html is pretty complicatedcomplicated

Let's look at a simpler example Let's look at a simpler example from the jah codefrom the jah code

Also 2 functions, but simplerAlso 2 functions, but simpler

00_ajax_demo.html is pretty 00_ajax_demo.html is pretty complicatedcomplicated

Let's look at a simpler example Let's look at a simpler example from the jah codefrom the jah code

Also 2 functions, but simplerAlso 2 functions, but simpler

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

Jah: Creating the objectJah: Creating the objectJah: Creating the objectJah: Creating the object

function jah(url,target) {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(); }} }}} }

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

Jah: What's called by Jah: What's called by the listenerthe listener

Jah: What's called by Jah: What's called by the listenerthe listener

function jahDone(target) {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 Notice that the only thing this looks

for is a state of 4 and a status of 200….for is a state of 4 and a status of 200….

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

HTTP Status CodesHTTP Status CodesHTTP Status CodesHTTP Status Codes

1xx are informational1xx are informational 2xx means success2xx means success 3xx means the user agent should 3xx means the user agent should redirect in order to complete the redirect in order to complete the transactiontransaction

4xx means a user agent error4xx means a user agent error 5xx means a server error5xx means a server error see:http://www.w3.org/Protocols/see:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.htmlrfc2616/rfc2616-sec10.html

1xx are informational1xx are informational 2xx means success2xx means success 3xx means the user agent should 3xx means the user agent should redirect in order to complete the redirect in order to complete the transactiontransaction

4xx means a user agent error4xx means a user agent error 5xx means a server error5xx means a server error see:http://www.w3.org/Protocols/see:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.htmlrfc2616/rfc2616-sec10.html

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

You can see this with You can see this with telnettelnet

You can see this with You can see this with telnettelnet

gilgamesh:~ hays$ telnet www.cs.unc.edu 80Trying 152.2.131.244...Connected to www.cs.unc.edu.Escape character is '^]'.GET /indse.htm HTTP/1.0

HTTP/1.1 404 Not FoundDate: Wed, 17 Sep 2008 11:41:59 GMTServer: Apache/2.2.3 (Red Hat)Content-Length: 287Connection: closeContent-Type: text/html; charset=iso-8859-1…

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

Walking through the Walking through the stepssteps

Walking through the Walking through the stepssteps

This example shows how the status This example shows how the status of the connection changesof the connection changes

Notice how a 404 is dealt with, Notice how a 404 is dealt with, versus how a security issue is versus how a security issue is dealt withdealt with

This example shows how the status This example shows how the status of the connection changesof the connection changes

Notice how a 404 is dealt with, Notice how a 404 is dealt with, versus how a security issue is versus how a security issue is dealt withdealt with

XMLHttpRequestWalker2.html

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

Another exampleAnother exampleAnother exampleAnother example

This is a simple page that calls This is a simple page that calls various calculators into a divvarious calculators into a div

Since I'm putting a whole web page Since I'm putting a whole web page into the div, I'm using innerHTMLinto the div, I'm using innerHTML

To code cleanly, you'd push just a To code cleanly, you'd push just a chunk of html code into the divchunk of html code into the div

This is just two functions and This is just two functions and some buttonssome buttons

This is a simple page that calls This is a simple page that calls various calculators into a divvarious calculators into a div

Since I'm putting a whole web page Since I'm putting a whole web page into the div, I'm using innerHTMLinto the div, I'm using innerHTML

To code cleanly, you'd push just a To code cleanly, you'd push just a chunk of html code into the divchunk of html code into the div

This is just two functions and This is just two functions and some buttonssome buttons

aaxmlhttprequest.html

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

GotchasGotchasGotchasGotchas

This has to run through a server This has to run through a server (the XMLHttpRequest object has no (the XMLHttpRequest object has no access to files)access to files)

In this version, if the text pulled In this version, if the text pulled in isn't XML, you get an error (but in isn't XML, you get an error (but it works)it works) This is due to the forcing of the type This is due to the forcing of the type of the XMLHttpRequest resultsof the XMLHttpRequest results

Which begs a question--do you need to Which begs a question--do you need to use XML?use XML?

And if not XML, what?And if not XML, what?

This has to run through a server This has to run through a server (the XMLHttpRequest object has no (the XMLHttpRequest object has no access to files)access to files)

In this version, if the text pulled In this version, if the text pulled in isn't XML, you get an error (but in isn't XML, you get an error (but it works)it works) This is due to the forcing of the type This is due to the forcing of the type of the XMLHttpRequest resultsof the XMLHttpRequest results

Which begs a question--do you need to Which begs a question--do you need to use XML?use XML?

And if not XML, what?And if not XML, what?

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

innerHTML.htmlinnerHTML.htmlinnerHTML.htmlinnerHTML.html

All of these examples use the All of these examples use the innerHTML property….innerHTML property….

Did I show you this?Did I show you this? This shows some simple This shows some simple manipulations of a page using the manipulations of a page using the innerHTML property outside of ajaxinnerHTML property outside of ajax

Note that pictures don't have any Note that pictures don't have any innerHTML (since there's no HTML innerHTML (since there's no HTML there)there)

All of these examples use the All of these examples use the innerHTML property….innerHTML property….

Did I show you this?Did I show you this? This shows some simple This shows some simple manipulations of a page using the manipulations of a page using the innerHTML property outside of ajaxinnerHTML property outside of ajax

Note that pictures don't have any Note that pictures don't have any innerHTML (since there's no HTML innerHTML (since there's no HTML there)there)

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

form_contents1_02.htmlform_contents1_02.htmlform_contents1_02.htmlform_contents1_02.html

The goal of this example is show a The goal of this example is show a form that uses php for validation of form that uses php for validation of datadata

First step (well, the first successful First step (well, the first successful step) was to create a simple html form step) was to create a simple html form for a useridfor a userid

Added a function to act as a triggerAdded a function to act as a trigger Wrote a simple php program, Wrote a simple php program, checkid.php, that reads a list into an checkid.php, that reads a list into an array and checks for the userid therearray and checks for the userid there

The goal of this example is show a The goal of this example is show a form that uses php for validation of form that uses php for validation of datadata

First step (well, the first successful First step (well, the first successful step) was to create a simple html form step) was to create a simple html form for a useridfor a userid

Added a function to act as a triggerAdded a function to act as a trigger Wrote a simple php program, Wrote a simple php program, checkid.php, that reads a list into an checkid.php, that reads a list into an array and checks for the userid therearray and checks for the userid there

This is inside the FormExample folder

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

The LogicThe LogicThe LogicThe Logic

checkid.php takes a GET variable, get_id, and checkid.php takes a GET variable, get_id, and checks that against a text file list of idschecks that against a text file list of ids

form_contents1_02.html has a form with a boxform_contents1_02.html has a form with a box onchange is the trigger, calls an ajax function onchange is the trigger, calls an ajax function (trigger this with a tab, a return submits the (trigger this with a tab, a return submits the form!)form!)

that function passes the content to checkid.php and that function passes the content to checkid.php and returns it's results to a div tag (or an alert)returns it's results to a div tag (or an alert)

thus it dynamically checks the validity without a thus it dynamically checks the validity without a reloadreload

This you can do with either innerHTML or DOM This you can do with either innerHTML or DOM referencesreferences

checkid.php takes a GET variable, get_id, and checkid.php takes a GET variable, get_id, and checks that against a text file list of idschecks that against a text file list of ids

form_contents1_02.html has a form with a boxform_contents1_02.html has a form with a box onchange is the trigger, calls an ajax function onchange is the trigger, calls an ajax function (trigger this with a tab, a return submits the (trigger this with a tab, a return submits the form!)form!)

that function passes the content to checkid.php and that function passes the content to checkid.php and returns it's results to a div tag (or an alert)returns it's results to a div tag (or an alert)

thus it dynamically checks the validity without a thus it dynamically checks the validity without a reloadreload

This you can do with either innerHTML or DOM This you can do with either innerHTML or DOM referencesreferences

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

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

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

The FunctionsThe FunctionsThe FunctionsThe Functions

Relied on the functions from the Relied on the functions from the mozilla examplemozilla example

The url that is called is the php The url that is called is the php script:script:

Relied on the functions from the Relied on the functions from the mozilla examplemozilla example

The url that is called is the php The url that is called is the php script:script:

function check_value(object, target_object) { makeRequest('checkid.php?get_id=' + object.value, target_object); }

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

Let the hairpulling Let the hairpulling begin…begin…

Let the hairpulling Let the hairpulling begin…begin…

The goal is to insert some text into the The goal is to insert some text into the formform

Easy with innerHTML, but with the DOM you Easy with innerHTML, but with the DOM you have to identify the object you want to have to identify the object you want to affectaffect

We talked some about the DOM architecture, We talked some about the DOM architecture, here's where things get more complicatedhere's where things get more complicated

Recall that you can reference objects by Recall that you can reference objects by ID, or out of an array (based on an ID, or out of an array (based on an object's position)object's position)

The goal is to insert some text into the The goal is to insert some text into the formform

Easy with innerHTML, but with the DOM you Easy with innerHTML, but with the DOM you have to identify the object you want to have to identify the object you want to affectaffect

We talked some about the DOM architecture, We talked some about the DOM architecture, here's where things get more complicatedhere's where things get more complicated

Recall that you can reference objects by Recall that you can reference objects by ID, or out of an array (based on an ID, or out of an array (based on an object's position)object's position)

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

Simple HTMLSimple HTMLSimple HTMLSimple HTML

From text to From text to DOM hierarchyDOM hierarchy

You can see You can see this with this with Firefox's DOM Firefox's DOM InspectorInspector

From text to From text to DOM hierarchyDOM hierarchy

You can see You can see this with this with Firefox's DOM Firefox's DOM InspectorInspector

from http://www.developer-x.com/content/innerhtml/from http://www.developer-x.com/content/innerhtml/

<body><body><div><div><p>Hello<em>Tim</em><p>Hello<em>Tim</em> How Are You?</p></div>How Are You?</p></div> <div>Developer-x.com</div><div>Developer-x.com</div></body></body>

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

form_contents1_03.htmlform_contents1_03.htmlform_contents1_03.htmlform_contents1_03.html

This version uses DOM:This version uses DOM:referencetarget_object.firstChild.nodeValuereferencetarget_object.firstChild.nodeValue

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

This version uses DOM:This version uses DOM:referencetarget_object.firstChild.nodeValuereferencetarget_object.firstChild.nodeValue

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

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

form_contents1_05.htmlform_contents1_05.htmlform_contents1_05.htmlform_contents1_05.html

Abstracted the checkid to Abstracted the checkid to checkvalues.php (as a general checkvalues.php (as a general check)check)

Added a password inputAdded a password input Added another parameter, Added another parameter, value_to_check, so that value_to_check, so that checkvalues.php would know what to checkvalues.php would know what to checkcheck

Played with focus settingsPlayed with focus settings

Abstracted the checkid to Abstracted the checkid to checkvalues.php (as a general checkvalues.php (as a general check)check)

Added a password inputAdded a password input Added another parameter, Added another parameter, value_to_check, so that value_to_check, so that checkvalues.php would know what to checkvalues.php would know what to checkcheck

Played with focus settingsPlayed with focus settings

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

innerHTML, DOM, what's innerHTML, DOM, what's the diff?the diff?

innerHTML, DOM, what's innerHTML, DOM, what's the diff?the diff?

InnerHTML is string based, whereas the DOM InnerHTML is string based, whereas the DOM manipulations are true objectsmanipulations are true objects This difference means in part that code This difference means in part that code dealing with DOM objects is both slower dealing with DOM objects is both slower and more verboseand more verbose

DOM objects are also harder to code for in DOM objects are also harder to code for in general--it's easy to change an existing general--it's easy to change an existing object, but to make a new section you have object, but to make a new section you have to create the objects, then populate themto create the objects, then populate them

DOM objects are easier to validateDOM objects are easier to validate InnerHTML isn't standards compliant, and may InnerHTML isn't standards compliant, and may never become part of a standard, but it's never become part of a standard, but it's likely not going away anytime soonlikely not going away anytime soon

InnerHTML is string based, whereas the DOM InnerHTML is string based, whereas the DOM manipulations are true objectsmanipulations are true objects This difference means in part that code This difference means in part that code dealing with DOM objects is both slower dealing with DOM objects is both slower and more verboseand more verbose

DOM objects are also harder to code for in DOM objects are also harder to code for in general--it's easy to change an existing general--it's easy to change an existing object, but to make a new section you have object, but to make a new section you have to create the objects, then populate themto create the objects, then populate them

DOM objects are easier to validateDOM objects are easier to validate InnerHTML isn't standards compliant, and may InnerHTML isn't standards compliant, and may never become part of a standard, but it's never become part of a standard, but it's likely not going away anytime soonlikely not going away anytime soon

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

Suppose we want to Suppose we want to change …change …

Suppose we want to Suppose we want to change …change …

If we want to make the text of If we want to make the text of the message ajax is inserting the message ajax is inserting into our form bold, we can't just into our form bold, we can't just add that to the javascript if add that to the javascript if we're using DOM objects as we're using DOM objects as referencesreferences

Can you guess why?Can you guess why?

If we want to make the text of If we want to make the text of the message ajax is inserting the message ajax is inserting into our form bold, we can't just into our form bold, we can't just add that to the javascript if add that to the javascript if we're using DOM objects as we're using DOM objects as referencesreferences

Can you guess why?Can you guess why?

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

Here's How to Do ThatHere's How to Do ThatHere's How to Do ThatHere's How to Do That This from This from javascript_functions2.jsjavascript_functions2.js

This from This from javascript_functions2.jsjavascript_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);

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

From the Optional Lab From the Optional Lab tonighttonight

From the Optional Lab From the Optional Lab tonighttonight

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

Other types of dataOther types of dataOther types of dataOther types of data

You can also call a url that returns other You can also call a url that returns other formats of data: tab text, raw text, etc.formats of data: tab text, raw text, etc.

You can write a server side script to give You can write a server side script to give you what you wantyou what you want

When we get to php we'll do some of this, When we get to php we'll do some of this, but an example is php_jah.htmlbut an example is php_jah.html

This file queries a php script, This file queries a php script, webconnection.php, that takes a url as a webconnection.php, that takes a url as a variable: variable: http://wwwx.cs.unc.edu/~hays/INLS672/samplhttp://wwwx.cs.unc.edu/~hays/INLS672/samples/ajax/webconnection.php?es/ajax/webconnection.php?target_url=www.unc.edutarget_url=www.unc.edu

You can also call a url that returns other You can also call a url that returns other formats of data: tab text, raw text, etc.formats of data: tab text, raw text, etc.

You can write a server side script to give You can write a server side script to give you what you wantyou what you want

When we get to php we'll do some of this, When we get to php we'll do some of this, but an example is php_jah.htmlbut an example is php_jah.html

This file queries a php script, This file queries a php script, webconnection.php, that takes a url as a webconnection.php, that takes a url as a variable: variable: http://wwwx.cs.unc.edu/~hays/INLS672/samplhttp://wwwx.cs.unc.edu/~hays/INLS672/samples/ajax/webconnection.php?es/ajax/webconnection.php?target_url=www.unc.edutarget_url=www.unc.edu

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

php.jahphp.jahphp.jahphp.jah

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

Having your cake and Having your cake and eating tooeating too

Having your cake and Having your cake and eating tooeating too

InnerXHTML is a pair of functions written by InnerXHTML is a pair of functions written by Steve TuckerSteve Tucker

http://www.stevetucker.co.uk/page-http://www.stevetucker.co.uk/page-innerxhtml.php#release0-4innerxhtml.php#release0-4

These functions can traverse a section of the These functions can traverse a section of the DOM of a page, and covert the results to a DOM of a page, and covert the results to a stringstring

They can also parse an html/xhtml string and They can also parse an html/xhtml string and produce the appropriate DOM objectsproduce the appropriate DOM objects

Other folks have similar tools, but this one Other folks have similar tools, but this one looked particularly nice and is very simple looked particularly nice and is very simple to useto use

See the innerXTML folder for an exampleSee the innerXTML folder for an example

InnerXHTML is a pair of functions written by InnerXHTML is a pair of functions written by Steve TuckerSteve Tucker

http://www.stevetucker.co.uk/page-http://www.stevetucker.co.uk/page-innerxhtml.php#release0-4innerxhtml.php#release0-4

These functions can traverse a section of the These functions can traverse a section of the DOM of a page, and covert the results to a DOM of a page, and covert the results to a stringstring

They can also parse an html/xhtml string and They can also parse an html/xhtml string and produce the appropriate DOM objectsproduce the appropriate DOM objects

Other folks have similar tools, but this one Other folks have similar tools, but this one looked particularly nice and is very simple looked particularly nice and is very simple to useto use

See the innerXTML folder for an exampleSee the innerXTML folder for an example

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

Upsides to AJAXUpsides to AJAXUpsides to AJAXUpsides to AJAX

Good way to get chunks of data Good way to get chunks of data into a web pageinto a web page

You can leverage the same code You can leverage the same code server and client sideserver and client side

Opens up lots of options for Opens up lots of options for doing simple stuffdoing simple stuff

It is pretty cool, and that It is pretty cool, and that counts for somethingcounts for something

Good way to get chunks of data Good way to get chunks of data into a web pageinto a web page

You can leverage the same code You can leverage the same code server and client sideserver and client side

Opens up lots of options for Opens up lots of options for doing simple stuffdoing simple stuff

It is pretty cool, and that It is pretty cool, and that counts for somethingcounts for something

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

Downsides to AJAXDownsides to AJAXDownsides to AJAXDownsides to AJAX

Caching issuesCaching issues Search enginesSearch engines ValidationValidation Bookmarking--since the page is Bookmarking--since the page is changed dynamically, the url changed dynamically, the url doesn't changedoesn't change

You can't leave the sandbox (at You can't leave the sandbox (at least not very easily)least not very easily)

Caching issuesCaching issues Search enginesSearch engines ValidationValidation Bookmarking--since the page is Bookmarking--since the page is changed dynamically, the url changed dynamically, the url doesn't changedoesn't change

You can't leave the sandbox (at You can't leave the sandbox (at least not very easily)least not very easily)

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

Some resourcesSome resourcesSome resourcesSome resources http://www.xml.com/pub/a/2005/08/19/ajax.htmlhttp://www.xml.com/pub/a/2005/08/19/ajax.html http://www.http://www.adaptivepathadaptivepath.com/publications/essays/archives/000385..com/publications/essays/archives/000385.phpphp

http://developer.http://developer.mozillamozilla.org/en/docs/AJAX:.org/en/docs/AJAX:Getting_StartedGetting_Started

http://www.onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprhttp://www.onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprequest.htmlequest.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_alternahttp://www.slayeroffice.com/articles/innerHTML_alternatives/tives/

http://www-128.ibm.com/developerworks/web/library/wa-http://www-128.ibm.com/developerworks/web/library/wa-ajaxtop1/index.html?ca=drs-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.htmlhttp://www.xml.com/pub/a/2005/08/19/ajax.html http://www.http://www.adaptivepathadaptivepath.com/publications/essays/archives/000385..com/publications/essays/archives/000385.phpphp

http://developer.http://developer.mozillamozilla.org/en/docs/AJAX:.org/en/docs/AJAX:Getting_StartedGetting_Started

http://www.onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprhttp://www.onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprequest.htmlequest.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_alternahttp://www.slayeroffice.com/articles/innerHTML_alternatives/tives/

http://www-128.ibm.com/developerworks/web/library/wa-http://www-128.ibm.com/developerworks/web/library/wa-ajaxtop1/index.html?ca=drs-ajaxtop1/index.html?ca=drs-

http://www.developer-x.com/content/innerhtml/http://www.developer-x.com/content/innerhtml/