dynamic data
Handling a response...seamlessly
The custom request handler callback function, handleRequest() in
this case, is called once an Ajax request finishes. In addition to signaling
that a request has completed successfully, this function’s job is to take
action based upon the response data returned by the server.
I get that the request handler is called
to take care of the Ajax response, but how
does it access the response data?
Methods of the AjaxRequest object have access
to the Ajax response data.
The request handler function provides access to the data passed back
in an Ajax response through two methods of the AjaxRequest
object, getResponseText() and getResponseXML().
AjaxRequest
request getReadyState()
getStatus()
getResponseText()
getResponseText()
getResponseXML() rGeespt othnesedaastarainwatnexAt.jax
send() getResponseXML()
Only one of these methods has access to viable data for any given Get the data in an Ajax response
response, meaning that the format of the data determines which as structured XML code.
method should be used. So getResponseXML() should be used
if the response data is XML, in which case getResponseText()
won’t return meaningful data. The same is true in the reverse if the
data is raw text, as opposed to structured XML code.
Knowing that XML code is structured a lot like HTML code, how
could you access the XML blog data in the request handler?
you are here 4 565
Download at WoweBook.Com
DOM saves the day
If XML is just a bunch of tags,
then can the DOM be used to
process the XML response data?
The DOM to the rescue
Ruby’s puzzling skills are certainly paying off because she’s dead-on with
her idea of using the DOM to process XML response data. The DOM
is all about manipulating HTML data as a tree of nodes. But there is
nothing HTML-specific about the DOM, which means that it can also be
used to work with XML as a tree of nodes. Ruby just has to think about
her YouCube XML blog data in terms of nodes.
<bl<<otagiu>ttlheo>rY>oPuuCzuzbleer-RTuhbey<B/laougthfoorr> Cube Puzzlers</title>
<entries>
<en<<tdbraoytd>ey>>0G8o/t14t/h2e00n8e<w/dcautbee>I ordered. It's a real pearl.</body>
</entry>
...
<en<<atdbraocytdu>eyb>>e0T9ht/ea2sk6ee/2di0rt0es8ae<ml/sfdajatupesa>trtk.eeWphagtet<tsitnrgonwge>idrodeesr<./.s.trnoonwg>I'imt seeing
m<eiamna?g<e/>bcoudbye>apart.png</image>
</entry>
</blog>
body
"... What" strong "it mean?"
author ToiHffhTetMcho<Lenbtobafdliooyngr>inmcgtaotansgtetvieniesngrtcatalcapcogahnsbit.lldaerinesn "does"
"Puzzler Ruby" Ruby needs to be able to extract the content from nodes of XML data,
which is a repetitive DOM task that is better suited to a function. There’s
The <author> tag no sense in adding a bunch of duplicate code to YouCube if it can be
acsonatacihnisldthteexatutehleomrennatm. e avoided.
566 Chapter 12
Download at WoweBook.Com
dynamic data
The getText() Function Up Close
The custom getText() function handles the drudgery of drilling into
an element (node) in the DOM tree and pulling out all of its content.
function getText(elem) { Tccoohnnetteaenlientms ietsnhtteoaebrlegemuemexnettnrtawchtoesde. Leloemopentth’srocuhgihldanlloodfes.the
var text = "";
if (elem) {
if (elem.childNodes) {
for (var i = 0; i < elem.childNodes.length; i++) {
var child = elem.childNodes[i];
if (child.nodeValue)
text += child.nodeValue; Add the child’s content
else { onto the text variable.
if (child.childNodes)
if (child.childNodes[0].nodeValue)
text += child.childNodes[0].nodeValue;
} Return the text variable, Iwgtfrihtaethbhifnetirrhaesetcathroeienlxdecthanicnolodddnetnm,oeojdnuvtseetsforno. m
} which contains all of the
} element’s child content.
}
return text;
}
Given that the XML response data has already been stored in a
variable named xmlData, write code to set the signature of the
YouCube blog to the name stored in the <author> XML tag.
you are here 4 567
Download at WoweBook.Com
Ajax responses exposed
Given that the XML response data has already been stored in a
variable named xmlData, write code to set the signature of the
YouCube blog to the name stored in the <author> XML tag.
Blog.prototype.signature = “by “ + getText(xmlData.getElementsByTagName(“author”)[0]);
TpsorhoeittositmgyunpsatetuobrbeejesicesttaotcfhlarBsosulogpghr.otpheerty, Use the custom getText() helper <Tsoahuejturhsetorsgh>roautlbadgtohinnelytfhbireestXonMoenLe. data,
function ftrooemxttrhaect<atuhtehotre>xttag.
content
Handling Ajax Responses
This week’s interview:
The handleRequest() Ajax request handler fesses up
Head First: We hear that you’re pretty good at handleRequest(): Well, it’s really not up to me.
responding to Ajax requests. What does that involve? Remember, I’m a custom function, so I’m different in
every application.
handleRequest(): When an Ajax request goes down,
I get tapped to handle the response, which often contains Head First: Why is that?
data sent from the server. My job is to first make sure the
request was carried out OK on the server, and if that handleRequest(): Because different applications use
checks out, then I get to dig through the data and take response data in different ways—it’s entirely application-
care of integrating it into the web page if necessary. specific. And so am I.
Head First: So you actually get called when a request Head First: Wait a minute, you mean someone has to
finishes? write you over again for every application?
handleRequest(): Oh yeah. In fact, I get called several handleRequest(): That’s right. It only makes sense
times throughout the request process, but most of the time because a shopping cart application would process its
people are only interested in me doing something at the Ajax responses very differently than a blog, for example.
very end. Ajax makes sure I get called once the server finishes with
the request, and from then on everything is completely
Head First: I see. And how do you know when that is? custom.
handleRequest(): Well, the AjaxRequest object has a Head First: So part of building an Ajax-powered web
couple of methods I can call to check the state and status page is creating a custom request handler?
of the request to make sure it has finished without any
problems. handleRequest(): Absolutely. That’s where most of the
real work in an Ajax application takes place.
Head First: Once that happens, how do you know what
to do? Head First: That’s very enlightening. I appreciate it.
handleRequest(): I’m always happy to respond.
568 Chapter 12
Download at WoweBook.Com
dynamic data
BE the JavaScript Annotator
Your job is to play JavaScript annotator and add
lots of annotations to explain exactly what is
going on in the handleRequest() function. 7 is a
magic number - are there 7 things
that lead to a successful request?
function handleRequest() {
if (ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
// Store the XML response data
var xmlData = ajaxReq.getResponseXML().getElementsByTagName(“blog”)[0];
// Set the blog-wide signature
Blog.prototype.signature = “by “ + getText(xmlData.getElementsByTagName(“author”)[0]);
// Create the array of Blog entry objects
var entries = xmlData.getElementsByTagName(“entry”);
for (var i = 0; i < entries.length; i++) {
// Create the blog entry
blog.push(new Blog(getText(entries[i].getElementsByTagName(“body”)[0]),
new Date(getText(entries[i].getElementsByTagName(“date”)[0])),
getText(entries[i].getElementsByTagName(“image”)[0])));
}
// Show the blog
showBlog(5);
}
}
you are here 4 569
Download at WoweBook.Com
be the solution
BE the JavaScript Annotator Solution
Your job is to play JavaScript annotator and add
lots of annotations to explain exactly what is
going on in the handleRequest() function. 7 is a
magic number - are there 7 things
that lead to a successful request?
tSoetthtehecobnlotgenstigninattuhree MchhaaeskccekoinmsugprlieettstehsdteasAtuecjacaxenssdrfeuqstlulyaetstbuys. TttggarhhegateebrEiaenltreirhtmsaeheoyenfntrlXiyrseBsMttouynLrTietnaee<dgmdNbatlaobianmgy,>es(o).
<author> tag.
function handleRequest() {
if (ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
// Store the XML response data
var xmlData = ajaxReq.getResponseXML().getElementsByTagName(“blog”)[0];
// Set the blog-wide signature
Blog.prototype.signature = “by “ + getText(xmlData.getElementsByTagName(“author”)[0]);
// Create the array of Blog entry objects cthGaooenltdggeatotlhldteoihrfbeelcotetghnletyernetitenosrtiereeayslec.mehIlteeenmnitstennrw’ttyhs.en, newcwheisecshary
var entries = xmlData.getElementsByTagName(“entry”);
for (var i = 0; i < entries.length; i++) {
// Create the blog entry
blog.push(new Blog(getText(entries[i].getElementsByTagName(“body”)[0]),
new Date(getText(entries[i].getElementsByTagName(“date”)[0])),
getText(entries[i].getElementsByTagName(“image”)[0])));
}
// Show the blog CtAenhrrdeeraaeotynfetoratbyhjneeaecwntad’rsbralapodyugsdhuo(sibt)injgemtcoettththfehooedr.
showBlog(5);
} 1 Create an AjaxRequest object.
}
CtboalollgditsehpneltarysihetoshwoeBnflotigvh(ee)lpaftaugenesct.tion
2 I ssue a GET request to retrieve
the blog.xml file from the server.
3 H andle the request. Done!
570 Chapter 12
Download at WoweBook.Com
dynamic data
YouCube is driven by its data Tabvohaoeiklasla/btlheefsjatst/v.ehrtstiopn:/s/owfwtwh.heeaYdofuCirusbtelabfsi.lceosma/re
Ruby is thrilled with the Ajax makeover of YouCube (it’s saving her a ton
of time) but she does have a nagging usability concern related to what
happens on the page while the blog data is loading.
<blog> The blog really works great with the
data separated out into XML code, but is
<<<eatnuitttrhlioeer>s>Y>PouuzCzulbeer-RuTbhye</Baluotghofro>r Cube Puzzlers</title> there a way to let the user know the blog
<entry>
<date>08/14/2008</date>
<body>Got the
</entry> new cube I ordered. It's a real pearl.</body>
<entry>
<date>08/19/2008</date> is busy loading? Just something to let
<body>Solved
</entry> the new cube but of course, now I'm bored and shopping
for a new one.</body>
<entry>
<date>08/16/2008</date> them know that the page is working.
<body>Managed
</entry> to get a headache toiling over the new cube. Gotta nap.</body>
<entry>
<date>08/21/2008</date>
<body>Found
</entry> a 7x7x7 cube for sale online. Yikes! That one could be
a beast.</body>
<entry>
<date>08/29/2008</date>
<body>Met up
</entry> with some fellow cubers to discuss the prospect of
a 7x7x7
<entry> cube. Mixed feelings.</body>
<date>08/27/2008</date>
<body>Went ahead
</entry> and ordered the scary 7x7x7 cube. Starting a mental
exercise
<entry> regimen to prepare.</body>
<date>09/3/2008</date>
<body>Attended
</entry> a rally outside of a local toy store that stopped carrying
<entry> cube puzzles. Power to the puzzlers!</body>
<date>09/5/2008</date>
<body>Got the
</entry> new 7x7x7 cube. Could be my last blog post for a while...
</body>
<entry>
<date>09/19/2008</date>
<<ibmoadgye>>Wcouwb,e7i7t7.tponogk</miemaagem>onth but the new cube is finally solved!</body>
</entry>
<entry>
<date>09/24/2008</date>
<body>I dreamed
</entry> last night a huge cube was chasing me, and it kept
yelling
<entry> my name backwards... Ybur!</body>
<date>09/26/2008</date>
<<ibmoadgye>>Tchuebseeapdarreta.mpsngj<u/sitmakgeee>p
</entry> getting weirder... now I'm seeing a cube take itself apart.
What <strong>does</strong> it mean?</body>
</entries>
</blog>
The blog ids antoaw... driven
by XML
.b..By utthesobmlaenukseprasgeartehcatonafpupseedars
while the data is loading.
Write the missing line of code in the loadBlog() function that displays
a “wait” image named wait.gif while the blog data is being loaded.
Hint: Use the main blog div, with an ID of "blog".
function loadBlog() {
ajaxReq.send("GET", "blog.xml", handleRequest);
}
you are here 4 571
Download at WoweBook.Com
sharpen solution
Write the missing line of code in the loadBlog() function that displays
a “wait” image named wait.gif while the blog data is being loaded.
Hint: Use the main blog div, with an ID of "blog".
function loadBlog() {
document.getElementById(“blog”).innerHTML = “<img src=’wait.gif’ alt=’Loading... ’ />”;
ajaxReq.send("GET", "blog.xml", handleRequest); iDinmnOaeMgreHiTtnaMtgLhwisiitschaesaaesicesoirnucpteloewuoesf’ereatthatadrndibitnuhgteeasn.
} The “cwoanitte”ntimwagheilecotmhpelebtloeglydraetpalaicseslotahdeing.
blog
Tietsnhhtueesreabiednlsoimgitnaodtpaelleatdtcaewtisaohifetlo.atgudishfeeinrigbmk.laonggoew
wait.gif
Q: The last YouCube blog entry contained an HTML Q: How does the ready state and status of an Ajax response
A:<strong> tag. How is that possible in XML code? A:work?
Remember that XML code can be used to represent any These two properties ultimately come from the
kind of data. In this case, knowing that the body of a blog entry is XMLHttpRequest object, and their job is to keep track of
getting injected into a web page, it is technically possible to include the state of the request, such as (0) uninitialized or (4) loaded, as
HTML tags that affect how the body appears on the page. In other well as the status of the request, such as 404 (not found) or 200
words, the body content of a particular blog entry can contain HTML (OK). It’s certainly possible to track these properties closely but
tags that are passed along as special formatting nodes in the XML it’s not necessary. All you need to know is that an Ajax request has
code. This is a fairly tricky prospect, however, since we’d have to completed successfully if the state is 4 (loaded) and the status is 200
reconstruct the HTML formatting nodes in the HTML code for the (OK). That’s why the handleRequest() function only leaps
page when injecting the XML data into the page. Instead of going into action if both of these conditions have been met.
down that path, the YouCube code elects to just pull the text content
out of any HTML tags, leaving the formatting behind. Ruby is still free
to add HTML formatting tags to blog content, possibly for a future
version of YouCube, but they are ignored for formatting purposes.
Their text does remain, which is a good thing.
572 Chapter 12
Download at WoweBook.Com
dynamic data
Dysfunctional buttons
Although the Ajax overhaul of YouCube has primarily taken place behind
the scenes, out of the view of YouCube users, there is apparently a user
interface issue that has come to light. More specifically, it seems the
buttons on the page aren’t quite working as they should.
Users are reporting that sometimes the
buttons don’t work. They click and nothing
happens. Not only that, but the blog isn’t
visible when the buttons are acting up.
What’s going on?
For some reason, the
iobsfunt’ttthovenissitbailmreeewn,’htaennwdoittrhkhienagbplpaoelgnl s.
Broken buttons = Unhappy users
Why aren’t the blog buttons working? When in Rrbeouatblytlyoimsnecoeafdlmstthboiustgpesrthoebtloemt.he
the process of the page loading do you think the
problem is occurring? you are here 4 573
Download at WoweBook.Com
when can I use it?
The buttons need data
The problem with the YouCube buttons is that they are only applicable
when blog data is available. And since the blog data is now loaded from an
external XML file, there will be a period of time, usually very brief, where
the page has no data. During this period, the buttons make no sense at all
and are only confusing users.
Can the buttons just
be disabled until blog
data is available?
Disabling the buttons is an excellent solution.
Disabling the buttons while the blog data is loading is a simple
and elegant way to solve the button problem. Since the Ajax
request to load the blog data is issued when the page first loads,
the buttons can start out disabled and can be enabled in the
handleRequest() function, which is when we know the
Ajax request has finished.
To actually carry out the disabling, we need to use the
disabled attribute of the <input> tag. This tag must be
set to "disabled" in HTML code to disable a button.
Conversely, it must be set to false in JavaScript code to
enable a button element.
574 Chapter 12 <input type="button" value="Search the Blog"
disabled="disabled" />
buttonElem.disabled = false;
Download at WoweBook.Com
dynamic data
JavaScript Magnets
Use the magnets to finish the code in the YouCube page so that the blog buttons are disabled
until the blog data finishes loading. You’ll need to use some of these magnets more than once.
<html>
<head> - The Blog for Cube Puzzlers</title>
<title>YouCube
<script type="text/javascript" src="ajax.js"> </script>
<script type="text/javascript" src="date.js"> </script>
<script type="text/javascript">
...
funicfti(oanjahxaRnedql.egReetqRueeasdty(S)ta{te() == 4 && ajaxReq.getStatus() == 200) {
...
// Enable the blog buttons
document.getElementById( ). = ;
;
document.getElementById( ). = ;
document.getElementById( ). =
true ...
}
}
...
</script>
</head>
<bo<<<dhiiy3mn>gpoYunostluroCctau=ydb"p=ece"u=l-b"oebaT.udhptBentlgooB"ngl"(oa)gli;td"f==>o""rYsoeCuauCrbucebhe"P"uvz/az>llueer=s"<S/eha3r>ch the Blog"
= onclick="searchBlog();" />
<input type="text" id="searchtext" name="searchtext" value="" />
<<diinvpuitd=t"ybpleo=g""b>u<t/tdoinv">id="showall" value="Show All Blog Entries"
= onclick="showBlog();" />
<input type="button" id="viewrandom" value="View a Random Blog Entry"
= onclick="randomBlog();" />
"search" </body>
</html>
"viewrandom" "showall" "disabled"
disabled false
you are here 4 575
Download at WoweBook.Com
JavaScript magnets solution
JavaScript Magnets Solution
Use the magnets to finish the code in the YouCube page so that the blog buttons are disabled
until the blog data finishes loading. You’ll need to use some of these magnets more than once.
<html>
<head> - The Blog for Cube Puzzlers</title>
<title>YouCube
<script type="text/javascript" src="ajax.js"> </script>
<script type="text/javascript" src="date.js"> </script>
<script type="text/javascript">
...
funicfti(oanjahxaRnedql.egReetqRueeasdty(S)ta{te() == 4 && ajaxReq.getStatus() == 200) {
... ). disabled = false ;
// Enable the blog buttons
document.getElementById( "search"
document.getElementById( "showall" ). disabled = false ;
document.getElementById( "viewrandom" ). disabled = false ;
...
}
}
...
</script>
</head>
<bo<<<dhiiy3mn>gpoYunostluroCctau=ydb"p=ece"u=l-b"oebaT.udhptBentlgooB"ngl"(oa)gli;td"f==>o""rYsoeCuauCrbucebhe"P"uvz/az>llueer=s"<S/eha3r>ch the Blog"
disabled = "disabled" onclick="searchBlog();" />
<input type="text" id="searchtext" name="searchtext" value="" />
<<diinvpuitd=t"ybpleo=g""b>u<t/tdoinv">id="showall" value="Show All Blog Entries"
disabled = "disabled" onclick="showBlog();" />
<input type="button" id="viewrandom" value="View a Random Blog Entry"
disabled = "disabled" onclick="randomBlog();" />
</body>
</html>
576 Chapter 12
Download at WoweBook.Com
dynamic data
Time-saving web-based blog additions
YouCube is now driven by dynamic data but Ruby has yet to fully
reap the reward. The true benefit of dynamic data in YouCube won’t
come home to her until she has the ability to use a web-based
interface for adding blog entries. Instead of editing an XML file to
add to the blog, she wants to be able to just enter a new entry on a
Web page and have it saved to the server.
I’m sick of editing files and then
FTPing them to the server just to update
my blog. I’d like to update YouCube from
the comfort of my own browser!
Edit code + Upload files = No fun!
Ruby envisions a web page just for her that allows her to post a new blog
entry by simply filling out a form. She could always be a click away from
updating her blog, and all she’d need is a browser. No text editors, no FTP
clients, just her cube puzzling enthusiasm.
Adding a new blog entry is as easy as filling
out the fields and clicking a button!
Tfpioehrcemesnfeowifeladbdslodfgobrelnottghrpeyatgdehartuease.es
How could Ajax be used to add XML blog entries
through a web page user interface?
you are here 4 577
Download at WoweBook.Com
clients and servers...again
Writing blog data
When thinking of a blog addition in terms of Ajax, it’s possible to imagine
an Ajax POST request that sends along the new blog entry data to the
server, after which the server writes the data to the blog.xml file as a
new blog entry. The Ajax response doesn’t really need to do anything in
this case since there is nothing to return.
Hang on! How exactly does the new blog entry
get written to the blog.xml file on the server?
I thought JavaScript couldn’t write files. And
isn’t JavaScript a client technology?
JavaScript isn’t the answer for writing to a
file on the server.
JavaScript isn’t an option for writing to the blog.xml
file on the server. In fact, you can’t even run JavaScript
code on the server. This is because JavaScript is a
client technology designed to be run solely in web
browsers. In this particular case JavaScript doesn’t help
us because we need to write a file on the server. This is
not an uncommon problem, which is why server-side
technologies are often used in conjunction with JavaScript.
What we need is a technology similar to JavaScript but
purely for doing things on the server. There are several
options out there but one comes to mind that isn’t too
complicated and works surprisingly well with XML data...
578 Chapter 12
Download at WoweBook.Com
dynamic data
PHP to the rescue...this time PHP is a scripting
technology that can
A scripting language called PHP offers everything we need to write blog carry out tasks on
data to an XML file on the server. The real task involved is to read the the server.
XML file, then add the new blog entry to the existing entries, and then
write all of the blog entries back out to the original file. But it all goes back
to receiving the new blog entry data on the server as an Ajax request from
the client browser.
Date: 10/04/2008 looking..."
Body: "I'm really
Image:
Client The new blog entry is sent to
the server as the data in an
Ajax POST request.
... brPuoHtlePoapnslatJyhasevaasSescrimrvieiplratr,
instead of the client.
Date: 10/04/2008
Body: "I'm really looking..." Server
Image:
Date: 10/04/2008 Date: 10/04/2008 looking..."
Body: "I'm really looking..." Body: "I'm really
Image:
Image:
Date: 10/04/2008
Body: "I'm really looking..." The PHP script on the server
Image:
takes the blog entry and file.
writes it to the blog.xml
<blog> You can think of PHP as sort of a server equivalent of
<title>... JavaScript in a sense that it runs on the server and is
<author>... capable of carrying out custom tasks... such as writing a
<entries> blog entry to a file as XML data!
<entry>
...
</entry>
...
</entries>
</blog>
blog.xml
you are here 4 579
Download at WoweBook.Com
server side goodness
Ready Bake On the server side of YouCube, a PHP script handles the details of adding a
PHP new blog entry to the XML blog data that is stored in the file blog.xml.
iLntooadthtehe$rraawwBXloMg vLardiaabtlae.
Check to see if <?php If the blog file doesn’t
the blog file exists. $filename = "blog.xml"; exist, create an empty
Convert the raw blog if /$(/rfaiLwloBeal_doegxtih=setfsbi(ll$oefg_igleeentnt_arcmioeen)st)efn{rtosm($tfhieleXnMaLmef)i;le XML blog document.
data into an XML
data structure, which }
is a lot like a DOM
tree in JavaScript. els/$$e/rraa{CwwrBBellaootgge=.a=n"<"e?<mxbpmltloygv>Xe<MrtLsiitdolonec=>u\Ym"oe1un.Ct0u\b"e e-ncTohdeinBgl=o\g"uftofr-8C\u"be?>P"u;zzlers</
title>"; .= "<author>Puzzler Ruby</author><entries></entries></blog>";
$rawBlog
}/$$$$i/xeeefmnnn$Alttt(edrrr$nd=yyy_t--Rrtn=>>EyheaaQ-ew$ddU>xddEanSmCCSdeilhhTdwm-ii[Cp>ll"hbleddiilen((mloXt""adgmrdbg(liaoe"eEetd"inlsey]mte-""arm>,,!gyea=end$s"atd_t",s(CRr"$hEi)$ariQp_alUsRcwdElEhB(SaQil"TsUloe[hEdgn"eS)tdsTn;ra([oyt$"d"e_ie)"Rm;]Ea)Qg;UeE"S]T)[;"XaAbsModdadLyct"hdh]iae)ldt)na;neowstdrbeulocwtgituerhneint. rtyhe
/$f/fwirWliretiet=(e$fftoihpleeen,e(n$$tfxiimrllee-n>baalmsoeXg,MLt'(ow)')t);h;e file
fclose($file);
wOivtehrwtrhietenetwhebblolgogdfatilae.
?>
addblogentry.php
Q: Do I have to use PHP to write files Q: Can I get away with using Ajax This fPilHePadscdrbiplotgeisntstryor.pehdp.in
the
on the server? without having to use a program on the
server at all? not require any server scripting. Most Ajax
A: No, not at all. There are all kinds of applications aren’t so lucky, so in most cases
A: In some cases yes but in most cases you will need to do some degree of coding
technologies out there for writing server on the server. The real issue is whether
scripts. You have Perl (CGI) and Java no. Keep in mind that all but the most or not the server can just send back an
servlets to name a few, and they can do all simple Ajax requests involve the server entire file, as is the case with blog.xml, or
of the same things that PHP can do. So if receiving data from the client and then if it has to somehow process data and do
you’re more comfortable with one of these doing something with it, such as looking something with it on the server, such as
other technologies, by all means use it to up something in a database or writing write it. The good news is that the kinds of
create the server-side component of your something to a file or database. The main scripts required on the server for many Ajax
Ajax applications. YouCube blog page is a good example of an applications are quite simple, and can often
Ajax request that is simple enough to be figured out without a mastery of a server
scripting technology.
580 Chapter 12
Download at WoweBook.Com
dynamic data
PHP has needs, too Running a PHP
script may require
Unlike JavaScript, which is inherently supported in modern browsers, some tweaks to
PHP support isn’t always a foregone conclusion on the server. So before your Web server.
you go posting PHP files to your Web server, it’s probably worth checking
with your system administrator or Web hosting service to see if PHP
is supported. If it isn’t, you’ll need to do all you can to get it added, or
possibly find a different Web server. The PHP script for YouCube simply
won’t work unless PHP is supported on the server.
PHP diobEnreetvfoecainnobiinaltiefsxetltayiatolnlninideangoedstedmistanili.ntl’tiYsi,tftoouyryr’oaloltuuAormrjsaaexylf!
Make sure your Web
server supports PHP.
Server
Support for PHP on your web server is the first hurdle. The second hurdle
is figuring out where to place PHP files on the server. In many cases it’s
OK to place PHP files in the same folder as your HTML web pages and
external JavaScript files. However, some PHP installations are pickier
and require PHP scripts to be stored in a special folder. Again, this is a
question that can be answered by a system administrator.
IssWntaeommbreeapnfPayogHlcedPasesrsaecrswreiyhpsoettursoercieanydnot.uhre addblogentry.php
Server www
Once you’ve figured out where the PHP file <html> <blog> ajax.js
should be placed on your web server, you’re <head> <title>...
ready to copy it there and continue building ... <author>... you are here 4 581
the YouCube blog addition web page. </head> <entries>
<entry>
<body> ...
... </entry>
</body> ...
</html> </entries>
youcube.html </blog>
blog.xml
Download at WoweBook.Com
the php part of the equation
Feeding data to the PHP script Data is fed to the
PHP script through
With PHP working on the server and the PHP script file in place, we can an Ajax request.
more closely examine what the PHP script needs in order to write data to
an XML file on the server. This will help us arrive at a design for the Ajax
request that provides the server exactly what it needs to carry out the task.
The PHP script is expecting the data for a new blog entry, which we know
consists of at least two pieces of information, and potentially three.
Date Date: 10/04/2008 looking..."
Body: "I'm really
The date of the blog entry.
Image:
Body
The body text of the blog entry.
Image oTsimnefhtunsoetatncatploAiafejcontakrthxamegJaresateevqtratuhvSeheecsartrtd.iapacsttaapncaorbdtee sdTtrceoahrqtierupaeetscsientefrtiovvaoeernrtdtp’shrhfeojeeocPebAedHsjsiaPsiinxtgs.
An optional image for the blog entry.
Server
This information must somehow get packaged up and sent to the server as
an Ajax request, where it is processed and saved to the blog.xml file.
lnbatAboeplolatooxpdggtteteahadhetreunisistomtboorrplemonoyrgitante.hthxtfhaiemrcestealbbsYhllflheoyeoeieguldentnC,pe.huawaeabdgneeddeids <blog> <entry>
<title>... <date>10/04/2008</date>
<author>... <body>I'm really looking...</body>
<entries> <image></image>
<entry>
... </entry>
</entry>
... ToeitfhntetcroPoynHtvtPheorestXcbirnMloigpgLt.txhtmaenaldkbfeloisslagecv.ainrge
</entries>
</blog>
blog.xml
The challenge is then to come up with a design for the blog addition web
page that first presents a user interface for entering a new blog entry, and
then gathers that information and shuttles it to the server in an Ajax
request. The good news it that we don’t really need to do anything in
response to the request other than maybe confirming that the new blog
entry has been saved successfully.
582 Chapter 12
Download at WoweBook.Com
dynamic data
Sketch out the design for the YouCube blog entry addition web
page, making sure to show exactly how the Ajax request and
response factor into the flow of data.
you are here 4 583
Download at WoweBook.Com
sharpen solution
The blog addition Web page Sketch out the design for the YouCube blog entry addition web
has form fields for entering page, making sure to show exactly how the Ajax request and
new blog entry data. response factor into the flow of data.
The Ajax request is a POST request consisting of
the following pieces of data:
* Blog date
* Blog body
* Blog image (content optional)
onclick! TtinohetthhbeeloPgseOdrSvaTetraraiessqusdeeansttta.
rbbCeluloqitgcutkeoaisnntdgdctitatohuiosebenesAAsdtejhdnaetx. Date: 10/04/2008 looking..."
Body: "I'm really
The Ajax response doesn’t Image:
trehteucrlnieanntyddoaetsna’tbenceaeudse
anything in return. sTbtulhhcoecegeucessslneifterunrlttylyhnhaaoatdtsditfbeheideee.snnew <blog>
<title>...
Server <author>...
<entries>
<entry>
...
</entry>
...
</entries>
</blog>
blog.xml
Ttbolhoegthseeenrtbvrleoyrg.awxsmriXlteMfsilLet.hdeanteaw
584 Chapter 12
Download at WoweBook.Com
Getting it up: Posting blog data to dynamic data
the server Date: 10/04/2008
Body: "I'm really looking... "
An Ajax POST request is a little more involved than a GET Image:
request because it requires sending data to the server. Although
the POST request supports different ways of packaging up data
for the server, the trusted technique of URL encoding the
data fields works just fine. This technique is the same one that
browsers use to pass fields of data to a server in the URL of a
web page, and is distinguished by the ampersand characters (&)
that are used to separate each piece of data.
"date=10/04/2008&body=I'm really looking forward... &image="
An individual pniaemcee/ovfaldueatpaair. Each piece of data is separated
consists of a from others by an ampersand.
This data format requires each piece of data to have its name and TtapynahdprisetmiosouffstthUtebRheeoLfsPfpeOeinccSciiaTofldiederddaetqadauseastta.,
value separated by an equal sign (=), and then each name/value pair is
separated from other data by an ampersand (&). The format is called
URL encoded, and has its own data type that gets set as the data type
of the Ajax POST request.
"application/x-www-form-urlencoded; charset=UTF-8"
With the blog entry data formatted into the URL-encoded format and
the data type of the POST request, we’re ready to put together the
request code and send the data to the server so that it can be saved to
the blog.xml file.
Package the following pieces of data into the URL-encoded format, suitable for a POST request.
releaseDate: 01/13/1989
title: Gleaming the Cube director: Graeme Clifford
you are here 4 585
Download at WoweBook.Com
satisfy your curiousity
Package the following pieces of data into the URL-encoded format, suitable for a POST request.
releaseDate: 01/13/1989
title: Gleaming the Cube director: Graeme Clifford
“title=Gleaming the Cube&releaseDate=01/13/1989&director=Graeme Clifford”
Q: If the YouCube blog addition script Q: Since it takes time for the server Q: Since the image is optional in the
doesn’t require any data from the server to process the Ajax request and save blog, does it always have to be passed
in the Ajax request, why bother handling the blog entry, is there a problem if the along to the server when adding a new
the request at all? Add button gets clicked again before the blog entry?
request finishes?
A: The reason is because knowing that a A: No, it doesn’t have to be. But keep in
A: Yes, it is a problem. Each click of the
request has completed is still very important. mind that there’s nothing wrong with sending
So even though we don’t need the server to Add button cancels the current Ajax request an empty piece of data where there is no
return any data in response to the request, and issues a new one. Although that may value following the equal sign in the URL
we still very much need to know if and when very well be the goal of someone clicking encoded string, like this:
the request has successfully completed. it twice, the user interface would be much
That’s what allows the script to know when to clearer if the option to click the button is "date=...&body=...&image="
display the alert that confirms the new blog simply removed while the request is being
entry addition. processed. So the code to add a new blog In this example, the image data field is still
entry should disable the Add button while the sent to the server even though it doesn’t
Q: Could a GET request also be used Ajax request is taking place, and then enable actually contain any data. This is where the
it again once the request has finished. Small PHP script on the server shines, because it
in the blog addition script? touches like this to the user interface of a is smart enough to know that the image field
JavaScript application can go a long way is empty, and therefore the new blog entry
A: Yes, technically it could. It’s still toward making it more intuitive and easier to doesn’t have an image.
use, resulting in happier users.
possible to send data along to the server in
a GET request, but you have to specify it Q: What happens to the spaces in
directly in the URL of the request. That’s not
really the problem—the problem is that GET the blog data that gets formatted into
isn’t intended to be used in situations where a URL encoded string? That seems to
the state of the server is changing. And in sometimes be a problem with URLs.
this case the state of the server is definitely
changing due to it writing a new blog entry A: The spaces don’t present a problem
to the blog.xml file. So a POST request is
the right approach if for no other reason than in this case because Ajax automatically
because it clearly indicates the intent of the handles processing the data and making
communication to the server. sure it gets to the server in a suitable format.
586 Chapter 12
Download at WoweBook.Com
dynamic data
Write the missing lines of code to finish the addBlogEntry() and
handleRequest() functions in the YouCube blog addition script.
function addBlogEntry() {
// Disable the Add button and set the status to busy
// Send the new blog entry data as an Ajax request
ajaxReq.send("POST", "addblogentry.php", handleRequest,
"application/x-www-form-urlencoded; charset=UTF-8",
);
}
function handleRequest() {
if (ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
// Enable the Add button and clear the status
// Confirm the addition of the blog entry
alert("The new blog entry was successfully added.");
}
}
you are here 4 587
Download at WoweBook.Com
sharpen solution
Write the missing lines of code to finish the addBlogEntry() and
handleRequest() functions in the YouCube blog addition script.
The Add button is disabled while a “Ttbuwhhsuaeeesirytps”itnkagamngtoeeowusndsssaiassgtoprehmleaeaseyyotsohatfairnhege.
blog entry is being saved to the server.
function addBlogEntry() {
// Disable the Add button and set the status to busy
document.getElementById(“add”).disabled = true;
document.getElementById(“status”).innerHTML = “Adding... ”;
This is // Send the new blog entry data as an Ajax request tAisheusesberdlvoegrtoePnpHtrProycsecasrnsidpt
a POST save it to the blog
request. ajaxReq.send("POST", "addblogentry.php", handleRequest, file on the server.
"application/x-www-form-urlencoded; charset=UTF-8",
“date=” + document.getElementById(“date”).value +
“&body=” + document.getElementById(“body”).value +
“&image=” + document.getElementById(“image”).value );
} Athsseemdabtlee,tbhoedrye,qaunedstimPaOgSeTfodramtaffierldoms.
function handleRequest() {
if (ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
// Enable the Add button and clear the status Check to make
sure the blog
document.getElementById(“add”).disabled = false; save request
document.getElementById(“status”).innerHTML = “”; finished
successfully.
// Confirm the addition of the blog entry
alert("The new blog entry was successfully added.");
}
} Enable the ahAradesadfnbinouiwtshtetodhnastaanvtdinhcgel.ear
the status
blog entry
588 Chapter 12
Download at WoweBook.Com
dynamic data
Blogging made easy The page confirms that
the blog entry was
Ruby can’t believe how much of a difference it makes being able to update successfully added.
her blog without having to open a file, edit code, and upload the file to the
server. Not only is her blog now truly data-driven, she is feeling a lot more
inspired to write some new blog data!
Rbluobgyeennttreyrsintthheenbewlog Dynamic blog
add web page. data is awesome!
The page lets the The new blog entry
user know the now appears on the
new blog entry is YouCube blog.
being added.
you are here 4 589
Download at WoweBook.Com
usability trumps all
Making YouCube more, uh, usable
You don’t become a third-degree cube puzzle black belt without a serious
attention to detail. So it’s not terribly surprising that Ruby wants to make
the blog addition page absolutely perfect. And Ruby has learned that
Ajax applications are known for their attention to detail when it comes to
usability. So she wants to make some improvements to the usability of her
new page so that it’s on par with modern Web pages.
I want to maximize my
blog entry efficiency so
that I can post faster, and
hopefully more often.
Maximizing YouCube blog data entry
Since the vast majority of blog entries are made in the present,
Ruby figures it will save her some precious keystrokes if the
date field of the blog form is automatically filled with today’s
date. And since she is going to use the current date for most blog
entries, she’d like to place the input focus on the body field of
the form. That way she can start typing away on a blog entry
the moment the page opens. Sure, none of these changes are
absolutely critical to the blog working, and they aren’t directly
related to Ajax, but they dramatically improve the “feel” of the
page, which is very much in the spirit of Ajax. Besides, it will help
ensure that Ruby keeps the blog up to date by posting regularly.
Auto-fill this field with
the current date.
stStheaatrtttRheuenbtiynerpciunatgn fimocmuesdhiaetreelyso
blog text.
590 Chapter 12
Download at WoweBook.Com
dynamic data
Auto-fill fields for your users
If you recall, the format of YouCube blog dates is MM/DD/YYYY,
which means we need to make sure to format the current date in the
auto‑filled date form field to the same format. So we need some code
to format the current date as MM/DD/YYYY.
You already created a Date method
that does this but it’s stored in the main
YouCube blog page. Is there a way to
share it with the blog addition page?
Sharing common code is always a good idea to
prevent duplication.
We certainly don’t want any duplicate code floating around in
YouCube that we have to maintain in two different places, so
sharing the date-formatting code between the two pages is a great
idea. And there is definitely a way to store the code in one place
and then share it in any page that needs it.
How would you share the shortFormat() code you are here 4 591
across both YouCube pages?
Download at WoweBook.Com
import export
Repetitive task? How about a function?
Sharing JavaScript code across multiple web pages involves breaking the code The familiar
out into its own file, or module, and then importing this file into each of the <script> tag is
pages. We’ve seen this done already with the AjaxRequest object, which is used to import
stored in the file ajax.js, and then imported with the following line of code: JavaScript code
that is stored in
The name of the JavaScript external files.
file is set to the src attribute
of the <script> tag.
<script type="text/javascript" src="ajax.js"> </script>
The shortFormat() method of the Date object can accomplish a
similar goal by being placed into a file named date.js, and then imported
into each of the YouCube web pages.
Date.prototype.shortFormat = function() {
return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
} var x;
var y;
function doX() {
...
}
A similar <script> tag that was used for the Ajax code can then be used function doY() {
in each of the YouCube pages to import the script code stored in date.js. ...
}
<script type="text/javascript" src="date.js"> </script> date.js
Tdthhatiesee.sjnisntgfilreiele<csaocrnretipeitmn>tpsotroatfge.dthweith itTinshhaasehnnaksersaexmtdteoeirJnsntaaotvlrwaifSnogiclpretli.aphcteesccooddee
It’s almost never a bad idea to break reusable JavaScript code into its own
file that can be shared in more than one place.
592 Chapter 12
Download at WoweBook.Com
dynamic data
<div id="blog"></div>
TfmohareimnsahYtoosrutbCFluoobgremepnaattgr()eie..sm. einthtohde
<input type="text" id="date" name="date" value="" size="10" /> .oc..fuarntrdehneittbadlolasgtoeafdoindrimttaihotensdptaahtgeee.field
Write the code for a function named initForm() that is called
in the onload event handler of the YouCube addition script. The
function must initialize the date field with the current date, and
then set the input focus to the body field.
you are here 4 593
Download at WoweBook.Com
sharpen solution
Write the code for a function named initForm() that is called
The date field is set in the onload event handler of the YouCube addition script. The
to the current date. function must initialize the date field with the current date, and
then set the input focus to the body field.
function initForm() {
document.getElementById(“date”).value = (new Date()).shortFormat();
tSoetthteheboindpyutfieflodc.us document.getElementById(“body”).focus();
}
Blog productivity soars The input focus is set
to the body when the
Ruby has finally reached utter satisfaction with the YouCube blog. Her page first loads.
blog is both data-driven and user-friendly thanks to Ajax and a ruthless
commitment to detail that only a master puzzler could muster. Twsehhteentdotathteeheipsacgaueurtrooepmnetantsd.icaatlely
I really, really
love my blog!
594 Chapter 12
Download at WoweBook.Com
JavaScriptcross dynamic data
Are you feeling dynaUminc?tiHtloewdaPbouutzszolmee data to Header Info 1
Header Info 2
go with that perky attitude? Crossword data, that is.
Get to it! etc...
11 22 55 66
88
33 44
77
99
1100 1111
1122
Across Down
22.. AA sseerrvveerr ssccrriippttiinngg tteecchhnnoollooggyy tthhaatt ccoommpplleemmeennttss 11.. TThhee MMLL iinn HHTTMMLL ssttaannddss ffoorr ............ llaanngguuaaggee..
JJaavvaaSSccrriipptt iinn AAjjaaxx aapppplliiccaattiioonnss.. 22.. AA rreeqquueesstt ttyyppee tthhaatt uussuuaallllyy iinnvvoollvveess aa ssttaattee
33.. TThhee sseerrvveerr''ss aannsswweerr ttoo aann AAjjaaxx rreeqquueesstt.. cchhaannggee oonn tthhee sseerrvveerr..
55.. TThhiiss kkiinndd ooff ffuunnccttiioonn ggeettss ccaalllleedd wwhheenn aann AAjjaaxx 44.. TThhee mmeetthhoodd ooff tthhee AAjjaaxxRReeqquueesstt oobbjjeecctt uusseedd ttoo
rreeqquueesstt iiss ffiinniisshheedd.. iissssuuee aa rreeqquueesstt..
88.. TThhiiss tteecchhnnoollooggyy ccaann bbee uusseedd ttoo WWeebb ppaaggeess mmuucchh 66.. TThhee ccuussttoomm oobbjjeecctt ccrreeaatteedd ttoo ssiimmpplliiffyy tthhee uussee ooff
mmoorree rreessppoonnssiivvee.. AAjjaaxx..
99.. TThhiiss kkiinndd ooff ddaattaa mmaakkeess WWeebb ppaaggeess mmuucchh mmoorree 77.. TThhee XX iinn XXMMLL ssttaannddss ffoorr tthhiiss..
iinntteerreessttiinngg.. 1100.. TThhiiss mmaakkeess <<bblloogg>>,, <<aauutthhoorr>>,, aanndd <<eennttrryy>>
1100.. TThhee ssttaannddaarrdd JJaavvaaSSccrriipptt oobbjjeecctt uusseedd ttoo ssuuppppoorrtt ppoossssiibbllee..
AAjjaaxx ffuunnccttiioonnaalliittyy.. 1111.. WWhheenn aann AAjjaaxx aapppplliiccaattiioonn aasskkss tthhee sseerrvveerr ffoorr
1122.. AA rreeqquueesstt ttyyppee tthhaatt uussuuaallllyy jjuusstt rreeqquueessttss ddaattaa ddaattaa..
ffrroomm tthhee sseerrvveerr..
you are here 4 595
Download at WoweBook.Com
JavaScript cross solution
JavaScriptcross Solution
Untitled Puzzle
Header Info 1
Header Info 2
etc...
1M 2P H P
AO 5C 6A L L B A C K
3R E 4S P O N S E
KE T J
U N 7A 8A J A X
P 9D Y N A M I C X
YR
TE
10X M L H T T P 11R E Q U E S T
MI EU
LN QE
12G E T U S
ET
S
T
Across Down
2. A server scripting technology that complements 1. The ML in HTML stands for ...... language.
JavaScript in Ajax applications. [PHP] [MARKUP]
3. The server's answer to an Ajax request. 2. A request type that usually involves a state
[RESPONSE] change on the server. [POST]
5. This kind of function gets called when an Ajax 4. The method of the AjaxRequest object used to
request is finished. [CALLBACK] issue a request. [SEND]
8. This technology can be used to Web pages much 6. The custom object created to simplify the use of
more responsive. [AJAX] Ajax. [AJAXREQUEST]
9. This kind of data makes Web pages much more 7. The X in XML stands for this. [ANYTHING]
interesting. [DYNAMIC] 10. This makes <blog>, <author>, and <entry>
10. The standard JavaScript object used to support possible. [XML]
5A192ja6.x A furenCqchutiaoepnsttaetlriyt1yp2.e[XthMatLuHsTuTaPllyREjuQstUrEeqSuTe]sts data 11. When an Ajax application asks the server for
data. [REQUEST]
from the server. [GET] Download at WoweBook.Com
dynamic data
Fold the page vertically Page Bender
to line up the two brains
and solve the riddle. What has Ajax given Ruby?
It’s a meeting of the minds!
AjaxRequest
I am falling apart, Let’s get you
one piece at a time! back into one piece.
Ajax has given Ruby so much, it’s
a hard thing to nail down. There’s dynamic
data for one thing, which has made
cube blogging a lot easier. Ruby can now talk
about her cube puzzles with ease.
you are here 4 597
Download at WoweBook.Com
continuing your journey
Where do you go from here?
Well you’ve made it through Head First JavaScript, and are ready to Left or right? Time for
continue on your journey of creating interactive user experiences with an if/else statement.
JavaScript and beyond...but where should you go next? Here are a few
things we think you might be interested in as you take your next steps
building and creating applications for the wild world wide web.
TRY the Head First JavaScript Forum
Exasperated over expressions? Overwhelmed by operators? Or are you
just curious to share your latest JavaScript creation with the Head First
community? Stop in for a spell at the Head First JavaScript forum at
Head First Labs (http://www.headfirstlabs.com) and join in one of
the discussions...or start a new one!
READ another book
You’ve got the essentials down, so get
ready to dig deeper into the ins and
outs of more advanced JavaScript.
JavaScript the Definitive Guide
JavaScript & DHTML Cookbook
LEARN more from other sites
Quirksmode www.quirksmode.org
Unfortunately, different browsers sometimes have their own way of
doing things with JavaScript. Get the scoop on JavaScript browser
inconsistencies at Quirksmode.
Mozilla JavaScript Reference
http://developer.mozilla.org/en/docs/JavaScript
It won’t be long at all until you’re venturing off the beaten bath and
need to find out more about built-in JavaScript objects. Explore every
nook and cranny of JavaScript with Mozilla’s online reference.
Prototype JavaScript Framework
http://www.prototypejs.org
Tempted to try a third-party library of reusable code to take JavaScript to
a whole new level? Prototype is one of the best, and it’s completely free!
598 Chapter 12
Download at WoweBook.Com
Index
Symbols AjaxRequest object 556–561
getResponseText( ) method 565
! (negation operator) 164, 165, 218 getResponseXML( ) method 565
handler 559
!= (inequality operator) 163 handleRequest( ) function 569–570
making sense out of 559
&& (AND operator) 217 postData 559
postDataType 559
++ (increment operator) 202 send( ) method 560
type 559
-- (decrement operator) 202 url 559
< (less than operator) 164 alert( ) function 19, 297
<= (less than or equal to operator) 164 alert boxes 297, 314
debugging 507–509
== (equality operator) 163 empty 162
versus = 164 resolving 163
problems debugging with 515
= versus == 510, 532 problems with 345
validation 309
> (greater than operator) 164
anonymous functions 279
>= (greater than or equal to operator) 164
apostrophes 21
|| (OR operator) 218 debugging 502, 532
escape characters 511
A
appendChild( ) method 361
action 6–7
arguments 252
Ajax 541 altering 260
asynchronous Ajax request 560 limits 260
connection between XML and Ajax 548
custom callback function 564 Array.sort( ) method 423
GET request 554–555
handleRequest( ) 565 arrays 198
Handling Ajax Responses 568 Arrays Exposed 200
PHP 579–584 as objects 420
running scripts 581–582 data stored in 201
POST request 554–555, 585 form array 293
ready state and status of an Ajax response 572 indexed 199, 201, 202
request/response 561 mapping array to seat images 204
YouCube project 563–564 mining data 199
URL encoding 585
XML 549
YouCube project 550–551
this is the index 599
Download at WoweBook.Com
the index boolean operators
arrays (continued) difference between normal and logic operator 219
searchable objects 424–432 parentheses 219
sorting 418–423
compare( ) function 421 break statements 178, 179, 212
function literals 422
two-dimensional 231–234 Browser Exposed 98
2-D Mandango Up Close 236–237
accessing data 233 browsers 89
Arrays Exposed 200 clearing variables 111
client-server interactions 86
asynchronous Ajax request 560 closing browser before timer expires 97
const keyword 46
attributes in forms 293 cookies 88
cookies and browser security 124
B difference between Web client, browser, client window,
Bannerocity project 290–292 and browser window 101
data validation 302 error console 491
dates 315–316 history 88
email addresses 334–337 JavaScript code 13
phone numbers 333 metrics 88
ZIP codes 310 page loading issues 522–523
eliminating three-digit years 330–331 resizing browser windows 106–107
non-empty validation 300–303 resizing iRock 102–103
placeOrder( ) function 313–314 running JavaScript code 88
validating length of data 305–306 syntax errors 500
trusting debugging messages 492
Blog object 404, 406, 408, 412–413 wrong-sized graphics 99–101
actions 441
adding images 476–479 bugs (see debugging)
adding methods 439–441
containsText( ) method 441–442, 450 built-in functions 21
extending objects 467–470
method overload 451 Bullet Points
signature property 460–465
sorting 472–473 AjaxRequest object 560
this keyword 451 arrays 202
toHTML( ) method 450, 456, 479 break statements 224
toString( ) method 450 callback functions 282
updated 443–444 capitalization 69
classes 459
blogSorter( ) class 473–474 className node property 379
client window 104
boolean data type 35 comments 173
compound statements 150
boolean operator logic 218 createElement( ) method 385
CSS style class 379
600 index
Download at WoweBook.Com
data types 49 the index
Date object 414
debugging in browser error console 498 character classes 336
DOM 364
events 21 checkWinner( ) function 504–505
form fields 307
function literals 282 child nodes 353, 363
function references 282
functions 21, 259 class-owned instance methods 471
global versus local variables 173
if statements 150 classes
initializing data 69 class properties versus global variables 464
innerHTML property 364 class properties versus instance properties 464, 466
loops 202, 224 properties 462–463
NaN (Not a Number) 69 storing methods 455
objects 399 versus instances 452–453, 459
prototypes 459
quotes and apostrophes 511 class methods 471
regular expressions 330 calling 474
return statement 269
sorting 432 className node property 379
syntax errors 511
this keyword 459 clearInterval( ) function 97
timers 104
two-dimensional arrays 235 client-server interactions 86
XMLHttpRequest object 560
clients 86, 89
buttons, disabling 574–576 Browser Exposed 98
controlling 89
C difference between Web client, browser, client window,
and browser window 101
callback functions 277, 281, 282 persistence 116
onload event handler 283 client window 99–101
versus normal functions 276 percentage of size 103
resizing iRock 102–103
callNum variable width and height 104
putting watch on 515 code separation 270–271, 274, 283
showing up as NaN 526–527
Code Up Close (Mandango project) 215
CamelCase 52, 62
comments 166, 167
capitalization 52, 62, 69 code inside 173
disabling code 527–529, 531
keywords 46 semicolon 173
objects 459
compare( ) function 421
changeScene( ) function 157, 162, 367
comparison operators 164
compound statements 148, 149, 150
inside for loops 201
variables inside 173
concatenating strings 64, 69, 76
you are here 4 601
Download at WoweBook.Com
the index
constants 40, 46–47 D
explicitly setting 49
uninitialized 60–61 data
versus variables 43
when to use 49 accessing form data 293
bad form data 298–299
const keyword 46 dynamic (see dynamic data)
entering into forms 295
constructors 402–403, 405, 459 non-empty validation 300–301
protecting integrity of 75
content, separating functionality, content, and tagging custom data with XML 543
presentation 270–271 validation 294–296, 302
context 169 alert boxes 297
dates 315–316, 329
continue statements 212 email addresses 334–337
length 305–306
converting text to number 65, 69 phone numbers 333
ZIP codes 310–312
cookieEnabled property 126 (see also regular expressions)
cookies 88, 112–115 data types 35, 45
browser detection 129
browser security 124 explicitly setting 49
greeting users with 120–121 objects 398
messages 129
names 125 data visibility 169
permanent 125
shared across browsers 125 Date object 97, 410–411, 414
touchRock( ) function 122–123
versus storing data on server 125 accessing parts of a date 417
where stored 125 converting objects to text 415–417
getDate( ) method 417
createElement( ) method 383, 385 getFullYear( ) method 417
getMonth( ) method 417
createTextNode( ) method 361, 371 shortFormat( ) method 592
sort comparison 423
CSS 6–7 toString( ) method 416
interactivity 8
separating HTML, JavaScript, and CSS code dates, validating 315–316, 329
270–271
using DOM to tweak CSS styles 372–373 debuggers 511
CSS style classes 375 debugging 486–536
manipulating individual styles 379
versus JavaScript classes 372, 374 = versus == 510, 532
alert boxes 507–509
curly braces
debugging 532 problems debugging with 515
missing 493–494 apostrophes 502, 532
switch/case statement 178 browsers 492
cheat sheet 505
custom objects 450–484 checklist 532
602 index
Download at WoweBook.Com
curly braces 532 the index
custom debugging console 517–520
Document Object Model (DOM) 352–392
debugging 521–523 appendChild( ) method 361
disabling code 527–529 changing node text 360–361
error console in browser 491 child nodes 353, 363
escape characters 503, 532 classifying DOM data 354
createElement( ) method 383
limitation 511 createTextNode( ) method 361
Firefox 489–491 DOM Building Blocks 362
Internet Explorer 488, 491 DOM tree 357
logic errors (see logic errors) element attribute 354
missing curly braces 493–494 ELEMENT node 354, 362
Opera 488 hierarchical tree of nodes 353
page loading issues 522–523 manipulating individual styles 379
parentheses 532 nodes 353
poor scripting 512–513 properties 357
quotes 501–502, 532 style property 377
runtime errors 524–525 types 354
Safari 488 visibility style property 377
shadow variables 530–532 properties 359
syntax errors (see syntax errors) removeChild( ) method 361
trying to references undefined variable or replacing node text with a function 368–369
TEXT node 354, 362
function 511 top node 354
typos 496, 497, 532 using DOM to tweak CSS styles 372–373
undefined variable error 495 Web standards 365
watch 508, 515
watching variables (see watching variables) DOM
extracting content from nodes of XML data 566
Debugging with Alert 509 XML 549
decisions 146 DOM Building Blocks 362
complex 218 dot operator 396–397
tiered 154
Duncan’s Donuts project 55–84
decision tree 152–153 calculation problems 58–59
fetching data from Web pages 71
path 161 intuitive user input 77
pseudocoding 158 parseDonuts( ) function 79
processing orders 56–57
devices, wrong-sized text and graphics 99–101 searching user input 78
string concatenation versus numeric addition 64
disabling code 527–529, 531
duplicate code, eliminating 254–256
div element versus span element 371
dynamically resizing images 108–109
<div> tag 346, 362
document.body.clientHeight 100
document.body.clientWidth 100
you are here 4 603
Download at WoweBook.Com
the index F
dynamic data 538–598 findSeat( ) function 206, 211, 258
Ajax (see Ajax)
HTTP request/response 561 Firefox, debugging 489–491
PHP 579–584
URL encoding 585–586 Fireside Chats
XHTML 545
bad form data 298–299
dynamic text decisions 370 class properties versus instance properties 466
for loops and while loops 226–227
E local versus global variables 172
normal functions versus callback functions 276
ELEMENT node 354, 362 persistent data storage 114
poor scripting 512–513
elements variables versus constants 43
IDs 71 XHTML 546
versus its value 76
floor( ) method 436, 437
email address validation 334
for loops 192–193, 226–228
empty alert box 162
resolving 163 code not being called 227
infinitely looping 201
empty strings 72 Mandango 197
encapsulation 472–473 forms 13, 292
error consoles 491 accessing form data 293
watching variables 516 alert boxes (see alert boxes)
arrays 293
errors attributes 293
logic (see logic errors) bad form data 298–299
runtime 524–525 data validation 294–296, 302
syntax (see syntax errors)
(see also debugging) alert boxes 297
dates 315–316
escape characters 503, 511, 532 ZIP codes 310–312
limitation 511 (see also regular expressions)
entering data 295
event handlers 278 fields 294
accessing form object 294
events 18 size 309
functions 272 generating events 296
onload 20, 105 help message, clearing 309
onresize 107–109 help text element 309
where they come from 21 HTML size attribute 309
wiring through function literals 279–280 non-empty validation 300–301
without connected code 21 onblur event 295–297
(see also callback functions)
604 index
Download at WoweBook.Com
the index
onchange event 295 naming conventions 249
onfocus event 295 normal functions versus callback functions 276
validating length of data 305–306 nuts and bolts of 247
parseFloat( ) 65
functionality, separating functionality, content, and parseInt( ) 65
presentation 270–271
decimal numbers 76
function literals 279, 281, 282 passing information 252
placeOrder( ) 313–314
event wiring through 279–280 purpose of 249, 260
onload event handler 283 referencing 273–275
replacing node text with a function 368–369
function references 278, 282 returning information 261–263
setInterval( ) 95, 97, 104
functions 19, 243–288, 398 setTimeout( ) 94, 104
trying to references undefined variable or
alert( ) 19, 297
arguments 252 function 511
turning into methods 441–442
limits 260 validateRegEx( ) 326–327
as problem solvers 246 versus compound statements 149
built-in 21 versus variables 274
callback (see callback functions)
calling 273 G
changeScene( ) 162
clearInterval( ) 97 getElementById( ) method 71, 76, 101, 102, 347, 352,
custom 358, 375
changeScene( ) 157, 367 getElementsByTagName( ) method 358
checkWinner( ) 504–505
createTextNode( ) 371 GET request 554–555, 561
findSeat( ) 206, 211
findSeats( ) 258 getSeatStatus( ) function 267–268
getSeatStatus( ) 267–268
getTemp( ) 262 getTemp( ) function 262
greetUser( ) 121
heat( ) 251, 263 getText( ) Function Up Close 567
initSeats ( ) 205
parseDonuts( ) 79 global scope 171
replaceNodeText( ) 369
setSeat( ) 257–258 global variables 169–173
showSeatStatus( ) 268–269, 272–273, 279 script level 173
touchRock( ) 24, 122–123 versus class properties 464
validateDate( ) 329
validateLength( ) 306 greetUser( ) function 121
validateNonEmpty( ) 300–303, 329
eliminating duplicate code 254–256 H
events 272
knowing when to use 249 Handling Ajax Responses 568
location in code 260
missing arguments 477 head of page, accessing code from 522–523
heat( ) function 251, 263
you are here 4 605
Download at WoweBook.Com
the index initializing data 69
constants 60–61
help message, clearing 309 variables 45
help text element 309 initializing loops 191
hierarchical tree of nodes 353 initSeats( ) function 205, 248
HTML 6–7 innerHTML property 348, 350, 352, 364, 408
accessing elements 347–348, 522 setting content 349
callback functions 277
interactivity 8 <input> tag, disabled attribute 574
separating HTML, JavaScript, and CSS code 270–
271 instances
size attribute 309 class properties versus instance properties 464, 466
versus XML 542 properties and methods 454–455, 463
XHTML 545 this keyword 454
versus classes 452–453, 459
HTTP request/response 561
interactivity
I HTML and CSS 8
without JavaScript 13
id attribute of <div> tag 346
Internet Explorer, debugging 488, 491
identifiers 50
capitalization 52 interpreter 86, 89, 493–494
unique 62
interval timers 93, 95, 97
IDs of elements 71 stopping 97
if/else statements 150 IQ calculator script 487–497
choosing between two things 141 missing curly braces 493–494
false condition 143 typos, debugging 496
formatting 143 undefined variable error 495–496
limitations 147
mulitple decisions 142 iRock project
multiple 154 100 in the iRock image size calculation 105
multiple else 143 alert( ) function 19
nested 175 cookie messages 129
cookies not available 126
if statements 138, 150 cookie writing 122–123
nested 155, 158 dynamically resizing iRock 108–109
semicolon 143 emotional behavior 90–91
events 18
<img> tag 204 greeting, specifying text for 23
greeting users with cookies 120–121
importing external scripts 119 instant replay 27
resizing 101–103
indexed arrays 199, 201, 202 resizing browser windows 106–107
storing data 34
infinite loops 201, 223
Mandango project 210
606 index
Download at WoweBook.Com
the index
J condition testing false 201
continue statements 212
JavaScript for (see for loops)
classes versus CSS style classes 372 infinite loops 201, 223
interpreter (see interpreter) initializing 191
separating HTML, JavaScript, and CSS code loop counter 213
270–271 nested loops 227
writing files to server 578 testing conditions 191
updates 191
JavaScript code while (see while loop)
browsers 13
comments inside 173 lowerCamelCase 52, 62, 249
constants (see constants)
data types 35 M
downside to storing JavaScript code in external
file 125 Mandango project 194–220
duplicate, eliminating 254–256
events 18 2-D Mandango Up Close 236–237
identifiers 50 better way to handle the three-seat check 217
importing from external files 592–593 break statements 212
missing curly braces 493–494 Code Up Close 215
running 88 continue statements 212
servers 89 findSeat( ) function 206, 211
single-line comment at end 173 findSeats( ) function 258
starting 13 from JavaScript to HTML 203–206
trying to references undefined variable or getSeatStatus( ) function 267–268
function 511 infinite loops 210
variables (see variables) initSeats( ) function 205, 248
mapping array to seat images 204
K onload event handler 283
seat images 204
keywords 44 seat initialization 205
capitalization 46 selSeat variable 206, 211
setSeat( ) function 257–258
L showSeatStatus( ) function 268–269, 272–273, 279
solo seat searching version 209
length property of a string 306–307 two-dimensional arrays 231–234
local variables 169–173 accessing data 233
logic errors 510–511, 525 markup language 542
poor scripting 512–513
Master of Patterns 325
loops 189–242
action 191 Math object 434, 437
break statements 212, 213, 224
Math Object Exposed 435
metacharacters 320–321, 324
you are here 4 607
Download at WoweBook.Com
the index
methods Array.sort( ) method 423
getElementById( ) 71, 76, 101, 102
knowing what script code can be put into 441 arrays 234
reload( ) 97 additional data in 234
storing in classes 455 data stored in 201
turning functions into 441–442 indexed 201
two-dimensional 234
milliseconds 95, 104
Blog( ) constructor’s argument list 478
mobile devices, wrong-sized graphics 99–101
blog data 548
N
Blog object 441
NaN (Not a Number) 62, 69 boolean operators, parentheses 219
navigator object 126 break statements 213
nested if/else statements 175 browsers 89
nested if statements 155, 158 callback functions 281
onload event handler 283
nested loops 227
callNum variable 511
new operator 405, 413
camel case and lower camel case 62
nodes 353
changing node text 360–361 charAt( ) method versus indexOf( ) method 432
multiple children 360
properties child nodes 363
childNodes 357
firstChild 357 classes versus instances 459
lastChild 357
nodeType 357 class properties
nodeValue 357 versus global variables 464
replacing node text with a function 368–369 versus instance properties 464
style property 377
types 354, 362 clearInterval( ) function 97
visibility style property 377
clients 89
No Dumb Questions controlling 89
! (negation operator) 165
100 in the iRock image size calculation 105 client window 101
addition versus concatenation 76
Ajax 580 closing browser before timer expires 97
request/response 561
AjaxRequest object 561 code separation 274
alert boxes 314
validation 309 comments inside code 173
arguments
altering 260 compound statements 149
limit on number of 260 inside for loops 201
608 index connection between XML and Ajax 548
constants, when to use 49
constructors 459
cookies
names 125
shared across browsers 125
where stored 125
createTextNode( ) function 371
CSS style classes 375
versus JavaScript classes 374
data types 49
Date object 414
sort comparison 423
debuggers 511
Download at WoweBook.Com
the index
debugging HTML size attribute 309
identifiers, unique 62
Firefox 491
IE 491 if/else statement
difference between a normal boolean operator and a false condition 143
multiple else 143
boolean logic operator 219
infinite loops 201
difference between Web client, browser, client window,
and browser window 101 interactivity without JavaScript 13
disabling code 531 interpreter 89
div element versus span element 371 interval timers 97
stopping 97
downside to storing JavaScript code in external
file 125 JavaScript code
browsers and 13
element versus its value 76 servers 89
single-line comment at end 173
error console in browser 491 starting 13
escape characters 511 knowing what script code can be put into methods
441
limitation 511
events loop counter 213
where they come from 21 loops
without connected code 21 code not being called 227
explicitly setting variables and constants 49 condition testing false 201
floor( ) method versus round( ) method 437 Math object 437
form object 294 NaN (Not a Number) 62
forms 13 nested if statements 158
fields 294 nested loops 227
generating events 296
onblur event 296 NOT operator 219
form field size attribute 309
null 165
function literals 281
object-oriented 461
functions 398
objects
built-in 21 constructors 405
knowing when to use 249 data types 398
location in code 260 dot operator 398
naming conventions 249 new operator 405
purpose of 249, 260 properties and methods 398
referencing 274
versus compound statements 149 onload event 105
versus variables 274
GET and POST requests 561 onload event handler 283
getElementById( ) method 76, 352, 358, 375 onmouseout event 375
getElementsByTagName( ) method 358 onmouseover event 375
global variables parseInt( ) function and decimal numbers 76
script level 173 permanent cookies 125
versus local variables 171
help message, clearing 309 PHP 580
help text element 309 placeOrder( ) function 314
HTML <strong> tag in XML 572 prototype objects 459
pseudocoding 158
quotes and apostrophes 21
you are here 4 609
Download at WoweBook.Com
the index
No Dumb Questions (continued) NOT operator 219
ready state and status of an Ajax response 572 null 165
regular expressions 324 missing function arguments 477
versus undefined 497
empty data 329
metacharacters 324 number data type 35
resizing iRock 101
<script> tag 13 numbers
searching for more than one substring 432 converting text to number 65
security 13 trying to add strings to 76
semicolon in comments 173
semicolon in if statement 143 numeric addition 64, 69, 76
setInterval( ) function 97
shadow variables 531 O
Stick Figure Adventure, variables 149
storing data on server versus cookies 125 object-oriented 461
strings as objects 432
switch/case statement 179 object-oriented design (OOP) 460, 461, 465, 467,
this keyword 309, 405, 459 470–475
timers 97
toLowerCase( ) in searchBlog( ) function 432 object-oriented script 399
toString( ) method 423
trying to add strings to numbers 76 object literals 413
trying to references undefined variable or
objects 395
function 511 arrays as 420
typos, debugging 497 Blog object 404, 406, 408, 412–413
undefined versus not defined 497 capitalization 459
undefined versus null 497 constructors 402–403, 405
URL encoding 586 converting to text 415–417
variables custom 400–401
custom (see custom objects)
inside compound statements 173 data types 398
uninitialized 49 Date object (see Date object)
when to use 49 dot operator 396–397
while loops 227 extending 467–470
width and height CSS style properties 105 Math object 434
YouCube blog addition script 586 new operator 405, 413
YouCube project properties and methods 396, 398
Add button 586 prototype 456–457
adding a new blog entry 586 searchable 426–427
Blog object 408 String object (see String object)
innerHTML 408 strings as 432
Show All Blog Entries button 408 toString( ) method 416
storing signature in property 464 within objects 413
non-empty validation 300–303 onblur event 295–297
bad form data 298–299
validateNonEmpty( ) function 301
610 index
Download at WoweBook.Com
the index
onchange event 295 Q
bad form data 298–299
quantifiers 322–323
one-shot timers 93
onfocus event 295 quotes 21
onload event 20, 105, 278 debugging 501–502, 532
onload event handler 280, 283 escape characters 503, 511
onmouseout event 375
onmouseover event 375 R
onresize event 107–109
Opera, debugging 488 radio call-in script 498–499
organizational object 434 alert boxes 507–508
callNum variable 507–508, 511
P checkWinner( ) function 504–505
debugging quotes 501–502
page loading issues 522–523 how the code is supposed to work 499
parentheses
random( ) method 436
boolean operators 219
debugging 532 random numbers 434–437
parseDonuts( ) function 79 learning more 437
parseFloat( ) function 65
parseInt( ) function 65, 77 Ready Bake JavaScript
decimal numbers 76 parseDonuts( ) function 79
PDAs, wrong-sized graphics 99–101 touchRock( ) function 24
persistence 112–115
clients versus servers 116 regular expressions 318–337
phone number validation 333 $ 320
PHP 579–584 ( ) 322
running scripts 581–582 * 322
placeOrder( ) function 313–314 + 322
placeOrder( ) function Up Close 314 . (dot) 320
POST request 554–555, 561 ? 322
presentation, separating functionality, content, and \d 320
\s 320
presentation 270–271 \w 320
problems, breaking down 244–245 ^ 320
prototype objects 456–457, 459, 468–469 {min,max} 329
pseudocoding 158 {n} 322
character classes 336
email address validation 334–337
empty data 329
escaping special characters 336
forward slashes (//) 320
metacharacters 320–321, 324
phone number validation 333
you are here 4 611
Download at WoweBook.Com
the index setTimeout( ) function 94, 104
regular expressions (continued) shadow variables 530–532
quantifiers 322–323
validating data with 326–327 showSeatStatus( ) function 268–269, 272–273, 279
ZIP codes 319
sort( ) method 420–421
reload( ) method 97
reloading pages, clearing variables 111 sorting 418–423
repetition (see loops) compare( ) function 421
replaceNodeText( ) function 369 function literals 422
request methods 554
resizing images 99–109 span element, versus div element 371
dynamically 108–109 <span> tag 302, 362
Return Exposed 264
return statement 262–264, 269 Stick Figure Adventure Code Up Close 351
reusable tasks 254–256
round( ) method 437 Stick Figure Adventure project 144–171
runtime errors 524–525 beginning 151
changeScene( ) function 157, 162, 367
S comments 166, 167
compound statements 148
Safari, debugging 488 createTextNode( ) function 371
scope 169, 170 CSS style classes versus JavaScript classes 374
curScene variable 146
global 171 decision tree 152–153, 382–383, 387
scripting 244 path 161
script level, global variables 173 pseudocoding 158
scripts, importing external 119 decision variable 146
<script> tag 13, 119, 592 div element versus span element 371
searchable objects 424–432 DOM (see Document Object Model)
security 13 dynamic text decisions 370
semicolon empty alert box 162
resolving 163
comments 173 empty options 376
if statement 143 id attribute of <div> tag 346
servers if/else statements 154
JavaScript code 89 if statements 155
persistence 116 innerHTML property 348–350
storing data on versus cookies 125 interactive options 371
setInterval( ) function 95, 97, 104 manipulating individual styles 379
setSeat( ) function 257–258 manufacturing HTML code 384
replacing node text with a function 368–369
612 index tiered decisions 154
unfolding the story 380–381
user decisions 146
variables 149
revisiting 170
Download at WoweBook.Com
storing data the index
constants (see constants)
data types 35 T
variables (see variables)
tabular data 233
string boundary 502
tasks, reusable 254–256
String object 413
charAt( ) method 426 text, converting to number 65
versus indexOf( ) method 432
indexOf( ) method 426–427 text data type 35
length 426
searching within 427 TEXT node 354, 362
toLowerCase( ) method 426
toUpperCase( ) method 426 this keyword 300, 309, 375, 403, 405, 459
Blog object 451
strings instances 454
as objects 432
concatenating 64, 69, 76 tiered decisions 154
debugging quotes 501–502
empty 72 timers 88
escape characters 503 closing browser before timer expires 97
length property 306–307 delay 94–96
searching for more than one substring 432 milliseconds 95
trying to add to numbers 76 interval 93, 95, 97
within strings 426 one-shot 93
setting 94
structure 6–7 time of day 97
understanding 92
style 6–7
toString( ) method 416, 423
style class 302
touchRock( ) function 24
style object 102–104 cookie writing 122–123
substrings 426 2-D Mandango Up Close 236–237
switch/case statements 143, 177–180 two-dimensional arrays 231–234
break statements 178, 179 2-D Mandango Up Close 236–237
curly braces 178 accessing data 233
default branch 178
Switch Exposed 180 typos, debugging 496, 497, 532
Switch Exposed 180 U
syntax 51 unary operator 219
syntax errors 500, 525 undefined
poor scripting 512–513 versus not defined 497
versus null 497
undefined variable error 495–496
unique identifiers 62
you are here 4 613
Download at WoweBook.Com
the index
URL encoding 585 W
spaces 586
watching variables 508, 515
user decisions 146 error consoles 516
decision tree 152–153 when it’s not enough 526–527
path 161
pseudocoding 158 Watch it!
tiered decisions 154 = versus == 164
break statements 179
user input 4–5 concatenating strings 64
intuitive 77 const keyword 46
searching 78 cookies 124
trusting 83 CSS style classes versus JavaScript classes 372
Date methods 417
V id attribute 346
regular expressions, escaping special characters 336
validateDate( ) function 329 resizing images 109
timer delay 95
validateLength( ) function 306 validating dates 329
while loops 223
validateNonEmpty( ) function 300–303, 329 ZIP codes 312
validateRegEx( ) function 326–327 Web client (see clients)
validation, data (see data, validation) Web pages
element versus its value 76
variables 40 fetching data from 71
clearing 111 interactions 86–87
creating blank 44 reloading 111
data types 45
explicitly setting 49 Web scripting 244
global 169–173
inside compound statements 173 Web standards 365
local 169–173
local and global variables with same name 530–531 while loops 222–229
location in code 168 code not being called 227
NaN (Not a Number) 62
scope (see scope) width and height CSS style properties 105
shadow 530–532
Stick Figure Adventure, revisiting 170 worms 124
trying to references undefined variable or
function 511 X
undefined variable error 495–496
uninitialized 49 XHTML 545–546
versus constants 43
versus fucntions 274 XML
when to use 49 Ajax 549
blog data 547
var keyword 44 connection between XML and Ajax 548
DOM 549
viruses 124
614 index
Download at WoweBook.Com