Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Head First Ajax
A Note Regarding Supplemental Files
Advance Praise for Head First Ajax
Author of Head First Ajax
How to Use this Book: Intro
Who is this book for?
Who should probably back away from this book?
We know what you’re thinking
We know what your brain is thinking
Metacognition: thinking about thinking
Here’s what WE did
Here’s what YOU can do to bend your brain into submission
Read Me
The technical review team
Acknowledgments
Safari® Books Online
1. Using Ajax: Web Apps for a New Generation
Web pages: the old-fashioned approach
Web pages reinvented
So what makes a page “Ajax”?
Rob’s Rock ‘n’ Roll Memorabilia
Ajax and rock ‘n’ roll in 5 steps
Step 1: Modify the XHTML
Step 2: Initialize the JavaScript
To set up the onclick behavior for the thumbnails, the initPage() function has to do two things
Step 3: Create a request object
Step 4: Get the item’s details
Let’s write the code for requesting an item’s details
Always make sure you have a request object before working with it
And here’s how that looks in our code...
The request object is just an object
Let’s break open() down a bit...
Hey, server... will you call me back at displayDetails(), please?
Use send() to send your request
The server usually returns data to Ajax requests
Traditional server-side interactions
Ajax server-side interactions
Ajax is server-agnostic
Use a callback function to work with data the server returns
Get the server’s response from the request object’s responseText property
Goodbye traditional web apps...
2. Designing Ajax Applications: Thinking Ajaxian
Mike’s traditional web site
Let’s use Ajax to send registration requests ASYNCHRONOUSLY
Update the registration page
Set the window.onload event handler... PROGRAMMATICALLY
Code in your JavaScript outside of functions runs when the script is read
What happens when...
And on the server...
Some parts of your Ajax designs will be the same... every time
createRequest() is always the same
Create a request object... on multiple browsers
Ajax app design involves both the web page AND the server-side program
What we’ve done so far...
What we still need to do...
The request object connects your code to the web browser
You talk to the browser, not the server
The browser calls back your function with the server’s response
Show the Ajax registration page to Mike...
The web form has TWO ways to send requests to the server now
Let’s create CSS classes for each state of the processing...
... and change the CSS class with our JavaScript
Changes? We don’t need no stinkin’ changes!
Only allow registration when it’s appropriate
3. Javascript Events: Reacting to your users
It all started with a downward-facing dog...
Ajax apps are more than the sum of their parts
Here’s Marcy’s XHTML...
Events are the key to interactivity
Connect events on your web page to event handlers in your JavaScript
Use the window.onload event to initialize the rest of the interactivity on a web page
Change those left-side images to be clickable
Use your XHTML’s content and structure
Every XHTML element is accessible in your JavaScript code as an object
Add the code for hideHint(), too
Tabs: an optical (and graphical) illusion
To make a tab active, we need to change the tab’s background to the “active” color
Use a for... loop to cycle through the images
CSS classes are the key (again)
Ummm... but the tabs aren’t < a >’s !
This broke our JavaScript, too, didn’t it?
Use a request object to fetch the class details from the server
Be careful when you have two functions changing the same part of a web page
Marcy wants the images on the left to change when users roll their mouse over the image
When you need to change images in your script, think “change CSS classes” instead
Links in XHTML are represented by <a> elements
We need a function to show an active button and hide a button, too
When you initialize the page, you need to assign the new event handlers
4. Multiple Event Handlers: Two’s company
An event can have only one event handler attached to it (or so it seems)
Only the LAST event handler assigned gets run
Event handlers are just properties
A property can have only ONE value
Assign multiple event handlers with addEventListener()
Your objects can have multiple event handlers assigned to a single event in DOM Level 2
The browser runs every handler for an event when that event is triggered
What’s going on with Internet Explorer?
Internet Explorer uses a totally different event model
attachEvent() and addEventListener() are functionally equivalent
addEventHandler() works for ALL apps, not just Marcy’s yoga page
Let’s update initPage() to use our new utility function
Use an alert() to troubleshoot
So what else could be going wrong?
Event handlers in IE are owned by IE’s event framework, NOT the active page object
attachEvent() and addEventListener() supply another argument to our handlers
Your event handlers get an Event object from attachEvent() and addEventListener()
We need to name the Event argument, so our handlers can work with it
You say target tomato, I say srcElement tomato...
So how do we actually GET the object that triggered the event?
5. Asynchronous Applications: It’s like renewing your driver’s license
What does asynchronous really mean?
A synchronous request for cola
An asynchronous request for cola
You’ve been building asynchronous apps all along
But sometimes you barely even notice...
Speaking of more server-side processing...
Oh, and password verification...
And... how about some eye candy, too?
(More) Asynchrony in 3 easy steps
We need two password fields and a <div> for the cover images
If you need new behavior, you probably need a new event handler function
With ONE request object, you can safely send and receive ONE asynchronous request
Asynchronous requests don’t wait on anything... including themselves!
If you’re making TWO separate requests, use TWO separate request objects
Right now, we disable the Register button in initPage()...
... and enable the button in the callback functions
Asynchrony means you can’t count on the ORDERING of your requests and responses
A monitor function MONITORS your application... from OUTSIDE the action
You call a monitor function when action MIGHT need to be taken
Right now, the username and password callbacks directly update the Register button’s status
Let’s have the callbacks run the monitor function...
... and let the monitor function update the Register button
Status variables let monitors know what’s going on
And now for our last trick...
Synchronous requests block ALL YOUR CODE from doing anything
First, we no longer need a “submit” button
Second, we need to register a new event handler for the button’s onclick event
Third, we need to send an ASYNCHRONOUS request to the server
Use setInterval() to let JavaScript run your process, instead of your own code
6. The Document Object Model: Web Page Forestry
You can change the CONTENT of a page...
... or you can change the STRUCTURE of a page
Browsers use the Document Object Model to represent your page
The document object is just an OBJECT
Here’s the XHTML that you write...
... and here’s what your browser sees
Your page is a set of related objects
Let’s use the DOM to build a dynamic app
We’re not replacing content, we’re moving it
You start with XHTML...
appendChild() adds a new child to a node
A new child gets a new parent... automatically
You can locate elements by name or by id
Can I move the clicked tile?
You can move around a DOM tree using FAMILY relationships
A DOM tree has nodes for EVERYTHING in your web page
Those spaces are nodes, too
The nodeName of a text node is “#text”
swapTiles() and cellIsEmpty() don’t take whitespace nodes into account
Did I win? Did I win?
But seriously... did I win?
7. Manipulating the DOM: My wish is your command
Webville Puzzles... the franchise
Woggle doesn’t use table cells for the tiles
The tiles in the XHTML are CSS-positioned
“We don’t want TOTALLY random letters...”
Our presentation is ALL in our CSS
Now the designers have options
We need a new event handler for handling tile clicks
Start building the event handler for each tile click
We can assign an event handler in our randomizeTiles() function
Property values are just strings in JavaScript
We need to add content AND structure to the “currentWord” <div>
Use the DOM to change a page’s structure
Use createElement() to create a DOM element
You have to TELL the browser where to put any new DOM nodes you create
The nodeName and nodeValue properties tell you about nodes
We need to disable each tile. That means changing the tile’s CSS class...
... AND turning OFF the addLetter() event handler
Submitting a word is just (another) request
Our JavaScript doesn’t care how the server figures out its response to our request
Usability check: WHEN can submitWord() get called?
You can’t submit a word if there’s no word to submit
8. Frameworks and Toolkits: Trust No One
So what frameworks ARE there?
Every framework uses a different syntax to do things
The syntax may change... but the JavaScript is still the same
To framework or not to framework?
The choice is up to you...
9. XML Requests and Responses: More Than Words Can Say
Classic rock gets a 21st century makeover
How should a server send a MULTI-valued response?
InnerHTML is only simple for the CLIENT side of a web app
You use the DOM to work with XML, just like you did with XHTML
XML is self-describing
10. JSON: SON of JavaScript
JSON can be text AND an object
JSON data can be treated as a JavaScript object
So how do we get JSON data from the server’s response?
JavaScript can evaluate textual data
Use eval() to manually evaluate text
Evaluating JSON data returns an object representation of that data
But there’s one catch...
JavaScript objects are ALREADY dynamic... because they’re not COMPILED objects
You can access an object’s members... and then get an object’s values with those members
You need to PARSE the server’s response, not just EVALUATE it
So which is the better data format?
11. Forms and Validation: Say what you meant to say
Marcy’s Yoga for Programmers... a booming new enterprise
Validation should work from the web page BACK to the server
You can validate the FORMAT of data, and you can validate the CONTENT of data
We need to validate the FORMAT of the data from Marcy’s enrollment page
Don’t Repeat Yourself: DRY
Let’s build some more event handlers
RETURN of SON of JavaScript
The value of a property can be another JavaScript object
Let’s warn Marcy’s customers when there’s a problem with their entry
If you don’t warn(), you have to unwarn()
IF there’s a warning, get rid of it
Duplicate data is a SERVER problem
You could do this with an asynchronous request...
... but what’s the benefit?
So we’re done now, right?
12. Post Requests: Paranoia: It’s your friend
There’s a villain in the movies
GET requests send request parameters across the network as clear text
Clear text is text... in the clear!
POST requests DON’T send clear text
GET requests send data in the request URL
POST requests send data separate from the request URL
The data in a POST request is ENCODED until it reaches the server
send() your request data in a POST request
Always check to make sure your request data was RECEIVED.
Why didn’t the POST request work?
The server unencodes POST data
We need to TELL the server what we’re sending
Servers get information from the browser via REQUEST HEADERS.
Servers send information to the browser using RESPONSE HEADERS.
Set a request header using setRequestHeader() on your request object
A. Leftovers: The Top Five Topics (we didn’t cover)
#1 Inspecting the DOM
Inspecting the DOM in Internet Explorer
Inspecting the DOM in Safari
#2 Graceful degradation
#3 script.aculo.us and the Yahoo UI libraries
script.aculo.us
Yahoo UI (YUI)
#4 Using JSON libraries in your PHP code
Using JSON in PHP 5.1 and earlier
#5 Ajax and ASP.NET
You don’t NEED ASP.NET Ajax to build Internet Explorer-compatible web apps
B. Utility Functions: Just Gimme the Code
utils.js: a work in progress
Index
About the Author
Copyright
← Prev
Back
Next →
← Prev
Back
Next →