Sie sind auf Seite 1von 21

My Note on Ajax page 1 of 21

My Note on Ajax
S. Saengamnatdej
October 27, 2009

"Ajax: A new approach to web applications" (18 Feb. 2005)


Examples: Google Maps, Google Suggest
faster & more responsive than traditional web-based app (bc exchange only small amount of data with
server, w/o requiring any page refreshes
"Asynchronous JavaScript and XML"
data exchanged btwn web browsers and web servers is passed asynchronously behind the scenes. So,
Ajax applications can submit requests to the web server w/o having to pause application execution and
can process the requested data whenever it is returned.

-use a special browser object "XMLHttpRequest", instead of a "form". ---enable asynchronous


communication
(client-side automation & effects: DHTML "a collection of technologies" --HTML, CSS, JavaScript, &
DOM) Ajax embraces all of the same technologies as DHTML & adds the XMLHttpRequest object &
XML into the mix.

components
1. html & css
2. XML (or plain text, or JSON: JavaScript Object Notation)
3. XMLHttpRequest
4. DOM (the HTML Document Object Model)
5. JavaScript

examples
1. search engines: A9.com(www.a9.com), www.ask.com, suggestion-based search engines: google
suggest, amazon zuggest (http://www.francisshanahan.com/zuggest.aspx),Dictionary: ObjectGraph
(http://www.objectgraph.com/dictionary/)
2. Google Maps
3. online DVD rental service: Netflix (www.netflix.com)
4. Virtual Desktop Applications : ajaxWindows (www.ajaxwindows.com) which also supplies
ajaxWrite: free online word processing, resembling microsoft word, for
(http://us.ajax13.com/en/ajaxwrite/ & ajaxSketch
5. photo management : www.flickr.com
6. message application : ajax im (www.ajaxim.net) instant messenger
7. online calendars :calendarHub www.calrendarhub.com

© SSAENG 2009
My Note on Ajax page 2 of 21

JavaScript
1. developed by Netscape Communication Corporation in 1995 with the name LiveScript, which is
changed to JavaScript.
2. ECMAScript version of JavaScript helped reduce incompatibility and confusion because of the
browser war from rivalry Microsoft Jscript.
2. designed to execute within web browsers.
2. for development of small programmes ("scripts"), which are embedded inside HTML pages
(head/body).
3. add interactive content to any web page.
4. an interpreted programming language (not converted into an executable form until the HTML page
that contains them is processed. (little slower)
5. an object-based programming language (it sees everything within HTML files and browser as
objects.) Every object has properties (describing feature/aspect) and methods (are collections of script
statements that when called upon to execute, enable the objects with which they are associated to
perform certain predefined actions.)
6. able to execute program code based on the occurrence of different events. (event is an action that is
initiated whenever the user interacts with your web application.)
7. case-sensitive programming language.

Places for JavaScripts


1. in Head section. to be executed automatically or conditionally. In most ajax, to ensure they are
defined and available before the rest of the HTML page loads, but do not automatically execute. (by
putting the JavaScript inside a function such as <script language = "javascript" type = "text/javascript">
function WarnUser() { window.alert("Don't"); }
2. in Body section.
3. in external files (plain text files of any length with a .js file extension)Then, use "src attribute" to call
it. This allows the creation of different JavaScripts for different browsers. (Advantages: 1.) makes the
page smaller and easier to manage. 2.) can be referenced and used by more than one Ajax application.
3.) later modification, w/o having to modify every page that references it.
4. in HTML tags. such as <body onLoad = document.write("Boo!")>

To prevent the display of JavaScript as part of the html page in the case of nonsupporting browser, use:
<script language = "javascript" type = "text/javascript">
<!-- Start hiding JavasScript statements
document.write("Boo!");
// End hiding JavaScript statements -->
</script>

function FunctionName(p1, p2, ...pn) {


statements;

© SSAENG 2009
My Note on Ajax page 3 of 21

return
}

In the parentheses, there are arguments. Return = optional (allows the function to return data back to
the statement that called it.)

when calling a function, only empty parenthesis may be used if there are no arguments ,otherwise many
arguments values, separated with comma, may be placed.

playerAge = DeterminePLayerAge();

JavaScript Events
onabort
onblur (An item loses focus)
onchange
onclick
ondbclick
ondragdrop
onerror
onfocus
onkeydown
onkeypress
onkeyup
onload
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onreset
onresize
onsubmit
onunload

Ajax uses <div></div> and <span></span> tags to dynamically update web page contents without
requiring refresh (facilitate dynamic text replacement). This can be done by naming the division.
example: <div name = "emphasis" style = "font style : bold">. by doing this, division can be
programmatically referenced and updated at pre-set locations as necessary. span division allows
applying changes inline.

Use array (an indexed list of values) to store any type of value supported by JavaScript.

© SSAENG 2009
My Note on Ajax page 4 of 21

"new" keyword is used in declaration of array: fruits = new Array(4); (4 means 4 value-storing
capability)

Two ways to create arrays:


fruits = new Array("lichee", "grape", "mangosteen", "banana", "apple", "langsat");
or
fruits = new Array(6);
fruit[0] = "lichee";
fruit[1] = "grape";
fruit[2] = "mangosteen";
fruit[3] = "banana";
fruit[4] = "apple";
fruit[5] = "langsat";

DOM
W3C DOM standard was published in 1998 and current version is DOM3 in 2004.
(www.w3c.org/DOM)

"When an HTML page is loaded, the browser automatically defines a collection of objects based on the
content of the HTML page. These objects are organized in a hierarchical top-down order, beginning
with the document object, tying all of the web pages' elements together in a tree-like structure. The tree
is made up of different elements, each of which represents a different web page object. Using the tree,
the browser maintains a map of connections that shows the organization of the web page, which
consists of a series of parent, child, and sibling relationships. Each of the objects in the DOM tree
provides access to methods and properties that you can use to programatically interact with and control
the objects. This provides you with the ability to make elements appear and disappear or to modify
them in other ways like changing their color, size, etc."

Key properties (used to identify different elements on the DOM tree and to retrieve element
(node)names, types, and values.)
childNodes A collection (e.g., array) of child objects belonging to an object.
firstChild The first child node belonging to an object.
lastChild An object's last child node.
NodeName The name assigned to an object's HTML tag.
nodeType Identifies the type of HTML element (tag, attribute, or text) associated with object
nodeValue Retrieves the value assigned to a text node.
nextSibling The child node following the previous child node in the tree.
previousSibling The child node that comes before the current child node.
parentNode An object's parent object.

© SSAENG 2009
My Note on Ajax page 5 of 21

Key methods (used to make modifications to the DOM tree, creating and appending new elements.
Modification takes place without refreshes.)
appendChild() Adds a new child node to the specified element.
createAttribute() Creates a new element attribute.
createElement() Creates a new document element.
createTextNode() Creates a new text item.
getElementByTagName() Retrieves an element based on its ID.
getElementById() Retrieves an element based on its ID.
hasChildNotes() Returns a true or false value depending on whether a node has children.
removeChild() Deletes the specified child node.

Accessing DOM elements


1. by ID
2. by using DOM properties
3. mixed approach

XMLHttpRequest

microsoft released in 1999


" to initiate and manage the submission of data requests to web servers and to monitor and handle the
receipt of server data."

XMLHttpRequest Methods
open(). Establishes a connection to a web server.
send(). Sends a request to a web server.

XMLHttpRequest Properties
readyState
A value between 0 and 4 indicating the state of the receipt of data from the web server, where a value of
0 means an uninitialized state (created, but not initiated), 1 means "sent" state (sent() method has yet to
execute), 2 means "sent" state (wait for data to be returned), 3 means a state in the process of receiving
data, and 4 means the data has been received (has finished receiving it). This property reports the value.

status
A status code indicating the overall status of the XMLHttpRequest object's data request, where a value
of 200 indicated that everything went well. (Any other value indicates that something has gone awry.)

responseText
Stores text data returned by the web server.
responseXML
Stores XML data returned by the web server.

© SSAENG 2009
My Note on Ajax page 6 of 21

onreadystatechange
Takes a function and calls on it to execute whenever the readystatechange event occurs. For an example
of use, see below.

How does it work?


1. Instantiating
To cover IE 5 or 6, the ActiveXObject should be included.

var Request = false;


if (window.XMLHttpRequest) {
Request = new XMLHttpRequest();
}else if (window.ActiveXObject) {
Request = new ActiveXObject("Microsoft.XMLHTTP");
}

------- or--------------
var Request = false;
try {
Request = new XMLHttpRequest(); //Try Firefox, Safari, Opera, etc.
}
Catch(e)
{
Request = new ActiveXObject("Microsoft.XMLHTTP");//Try ActiveX(IE)
}

2. Checking if a valid XMLHttpRequest has been successfully instantiated and Opening a New
Connection.
syntax for opening a connection.
open("method", "url" [, asyncFlag [, username [, password]]])

method --> the http method to be used to establish a connection with the web server ("GET" for
retrieving a moderate amount of data, "POST" for large amounts of data)
url --> The URL of the file to be opened on the web server. It can be absolute (exact location) or
relative (only a file name, in the same location as the application.)
asyncFlag --> An optional value that when set to true (default) sets up an asynchronous connection (a
value of false dictates a synchronous connection), as explained more below.
userName --> An optional username if required by the web server
password --> An optional password if required by the web server.

The XMLHttpRequest object always creates asynchronous connections with the web server, unless you
explicitly tell it not to by assigning a value of false to asyncFlag.

© SSAENG 2009
My Note on Ajax page 7 of 21

example
if(Request) {
Request.open("GET", "Scores.txt");
.
.
.
}

3. Setting an anonymous function. (Waiting for sever 's response)


This function automatically executes whenever there is the state of the request, allowing you to add
script statements designed to monitor and keep track of the progress of the application's data request.

Request.onreadystatechange = function() {
if (Request.readyState == 4 && Request.status == 200) {
.
.
.
}
}

4. Specifying the type of data that the application expects o receive (by using responseText or
responseXML)
example
RequestObj.innerHTML = Request.responseXML;

5. Submitting the request & retrieving the data (executing send() method which initiates the download
process.)
syntax
send("string")

When working with the "get" mode, the "string" value will always be "null".

<form>
<input type ="button" value ="Answer is Here"
onclick = "retrieveANSWER('ANS1.txt', 'DivTarget')">
</form>
<div id="DivTarget"> </div>
The button's onClick event handler passes the function two arguments. The first argument specifies the
name of a text file to be downloaded from the web server, and the second argument specifies the id
associated with a pair of <div> </div> tags located in the body section where the contents of the text
files will be displayed once processed by the function.

© SSAENG 2009
My Note on Ajax page 8 of 21

Concurrently fetching multiple sets of data from the server.


var Request1 = false;
var Request2 = false;
if(window.XMLHttpRequest) {
Request1 = new XMLHttpRequest();
Request2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
Request1 = new ActiveXObject("Microsoft.XMLHTTP");
Request2 = new ActiveXObject("Microsoft.XMLHTTP");
}

or use an array instead-------------------


var aRequests = new Array();
if(window.XMLHttpRequest) {
aRequests.push(new XMLHttpRequest());
} else if (window.ActiveXObject) {
aRequests.push(new ActiveXObject("Microsoft.XMLHTTP"));
}

Leveraging Ajax Frameworks


A framework is a collection of programme code that is designed to simplify application development.
Ajax frameworks
• consist of collections of JavaScript functions that you can call upon from within your applications.
• include a sever-side component that includes program code that facilitates server-side database
searches and data manipulation and processing.
• range from very small libraries to large, robust code libraries that provide everything needed to build
complex applications.
• range from small general-purpose frameworks (free download) to large commercial libraries.
(hundreds of types)
• allow incorporating pre-written JavaScript functions into web pages and JavaScript code.
• popular : Yahoo!User Interface Library (YUI) and Dojo
http://developer.yahoo.com/yui/
http://dojotoolkit.org
• Use the framework:Extract files from the download locally or on a web server. Include <SCRIPT
TYPE="text/javascript" SRC="dojo/dojo.js"></SCRIPT> and you're on your way.
∘ copy the code files that make up the framework to your web server
∘ then, add a reference to it in your Ajax application using a statement like the one shown here:
<script langauge = "javascript" type = "text/javascript" src="cba.js">
.
.
</script>

© SSAENG 2009
My Note on Ajax page 9 of 21

• CBA is a small free framework (128 Kb) http://www.crossbrowserajax.com download "CBA.js" and
upload it tothe same folder on your web server where your ajax applications are stored.
• this is how to use it (from the cba_hm_page):

<head>
<script src="cba.js"></script>
</head>
<span id="myElement"></span><a href="javascript://" onClick="
cbaUpdateElement('myElement','userinfo.php?data=mydata');
">Update myElement</a>

This function (cbaUpdateElement) handles all communication with the web server and makes sure that
the text that is returned by the web server is dynamically added to the web page. This helps
significantly reducing the size and complexity of your ajax applications.

Designing the application


1. Create a new HTML page.
2. Create the application's text files.
3. Create the application's JavaScript and defining global variables.
4. Set up the XMLHttpRequest object.
5. Download and display the game's challenge sentences.
6. Evaluate the player's score.

Steps of writing
Step 1 : Writing the application's html.
Step 2 : Creating the application's server-side text files.
Step 3 : Beginning work on the application's JavaScript.
Step 4 : Instantiating the XMLHttpRequest Object.
Step 5 : Retrieving and displaying challenge sentences.
Step 6 : Grading the results of the ajax typing challenge.

Manipulate graphics
ajax is limited to working with text and XML, by using DHTML it can dynamically download and
display graphics.
Text files have contents of images (??change file extension of images to .txt??) The text that is
downloaded is either a string of "frymo1.JPG" or "frymo2.JPG". Finally, a new <img> tag is created
and the value of the text string downloaded from the server is appended to the tag. The new <img> tag
is placed inside a pair of <div> </div> tags. The end result of altering the web page DOM tree in this
manner is that the browser immediately downloads the graphic files specified in the new <img> tags
and displays them.

© SSAENG 2009
My Note on Ajax page 10 of 21

Work with PHP


Ajax, a client-side programming tool, can interact with web server programs that accept and process
input provided by Ajax applications and then return data for the Ajax application to process.

Instead of getting "text file', it can get the 'php file' (placed in the same folder). Advantage of php
script: its capability of performing all kinds of complex operations, like reading text files and retrieving
data from a server database. server-side programs can also process application data retrieved from files
and databases before returning it back to an ajax application.

Send data to web servers for processing


Aj can be used to call upon a server-side php script and pass it some data for processing.
two options:
1. ) use XMLHttpRequest object's open() method's GET option to call on server-side programs and
pass them data for processing results in URL-encoded data.
• URL encoding technique: data being sent is appended to the end of the url string that is used to
connect to the web server. (The URL-encoded data is insecure and easily readable, so it is not a good
option for applications that have to deal with highly confidential data.)
• with '?' before the data, a 'data=value' format, a '&' to separate the multiple 'data=pair' arguments, and
a '+' replace those blank spaces. example: "http://www.mywebser.com/tellstory.php?
story=traveling+in+Thailand " (this can be done with JavaScript's escape method: x = escape("traveling
in Thailand")
• in the php script, $_GET array can be used to analyze the argument passed to the program and
execution is taken place. The Ajax application captures the outputted text string returned by the php
script and displays it in the html page's <div></div> tags.
2. ) use open() method's POST option (sending encoded data back to web server.)
• secure: data sent is internally encoded.
• not require "var url = "options.php?category=" + category; (as in the case of "GET")
• instead, the php is in "Request.open("POST", "option.php");" and
"Request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');"
• change "Request.send(null);" to "Request.send("category=" + category);"

Executing server-supplied javascript


ajax application can download and execute javascript statements.
• download the text representing the javascript statements and pass them to a JavaScript function
named 'eval()'. The function then re-evaluates the text statements passed to it and executes them as
JavaScript statements.
• convenient, but if possible, do not use this. It's good to make server-side programs independent of
their client-side counterparts.
• It may be used to create an Ajax application that works with any number of third-party web services
(Google Maps, Google suggest, etc).
• In Ajax: "if(Request.readyState == 4 && Request.status == 200) {
eval(Request.responseText);" Example: This php script contains a function named 'feedQuiz'.

© SSAENG 2009
My Note on Ajax page 11 of 21

Once downloaded, the JavaScript statement is passed to the eval() method, which executes it. (There is
a function named 'feedQuiz()' in the Ajax application that will call upon it to execute. <?php
echo "feedQuiz('Which viruses are RNA viruses?', 'Coronaviruses')";
?>

Google Suggestion
1. The web server returns the text string consists of a JavaScript function named
'window.google.ac.Suggest_apply()'
2. syntax
window.google.ac.Suggest_apply(ignoreVar, keyword, aResults, aEmpty)
3. this function name does not work in ajax application. Because based on the name of the function, the
browser is instructed to call upon the 'window' object's 'google' prperty and no such property exits. To
solve this, rename 'window.google.ac.Suggest_apply()' to the name of a function in the ajax application
prior to passing the web server's output string to the JavaScript 'eval()' function.

Design the application


1. create a new HTML page.
2. Format the display of Google Suggest results using CSS.
3. Begin work on the application's JavaScript and instantiating an XMLHttpRequest object.
4. Create a function to capture user keystrokes and pass them to the application's PHP script.
5. Process the list of terms returned by Google suggest.
6. Submit the term or phrase selected by the user.
7. create the application's PHP file.

Steps
1. Writing the application's HTML.
2. Using CSS to control search results. (apply a background color, width, and border style to the
<div></div> tags. This should be under the <title></title> tags in the head section.
3.Creating the application's JavaScript and instantiating the XMLHttpRequest Object. (in head section)
4. Capturing and passing along user keystrokes. (retrieve event data by using the 'window object's event
property' The javascript '?' operator is used to evaluate and assign a value to 'keystroke'. The '?'
operator is one of the three logical Boolean operations supported by JavaScript. Its purpose is to assign
either of two possible values to a variable based on the result of an evaluated condition, using the
following syntax.
var result = condition ? value : alternativeValue;
Example: var searchString =
(keyStroke.target) ? keyStroke.target : keyStroke.srcElement;
5. Processing the list of terms provided by Google Suggest. (Use 'substr() function to remove the first
30 characters of the data stored in the response string (e.g., window.google.ac.Suggest_apply). Next,
the name of the 'ProcessGoogleResults()' function is appended to the beginning of the string, which is
then processed by the eval() function.
6. Submitting the search term or phase selected by the user.

© SSAENG 2009
My Note on Ajax page 12 of 21

The function 'ProcessGoogleResults()' is executed whenever the output string returned from Google is
evaluated and executed (as a JavaScript statement).
7. Creating the application's PHP script. The 'google.php' is to pass the application's search string to
Google Suggest and to collect and return the results of that submission back to the application for
processing. (The security rules prevent browser applications from directly accessing server programs
(e.g, Google's server) that run on different internet domains. This php script let your web server handle
the exchange of information on your behalf, server to server. (The 'fopen()' function is for submitting
your application's search term to Google Suggest and it stores the returned output in the $objRef
variable. The while loop then processes the contents of the data stored in the variable by the 'fgets()"
function retrieves each search term or phrase and and the 'echo' command returns them as text to the
ajax application. After retrieving all the output from Google, the 'fclose()' function disconnects to
google and the execution is halted.

XML
eXtensible Markup Language
A general-purpose markup language for storing and transporting (any amount of)data in a platform-
independent manner. (organize the different types of elements that make up documents.)
Learn how to:
• create XML files
• basics of XML element syntax
• formulate XML tags that include text content and optional attribute data (add attributes to XML tags).
• access the contents (access attribute data) using Ajax.
• problem with white space and how to avoid.
• use different JavaScript properties to navigate and extract data from XML files.

XML's rules
• have one root element ("document element")
• attributes
∘ in single or double quotation marks
∘ appear once in an element tag.
• tag names
∘ cannot start with a number.
∘ cannot include blank spaces or quotation marks
• all elements must be properly nested.
XML element syntax
<openingtag attribute="value">content</ closingtag>
Use blank to separate attributes. 'content' represents optional text. Case-sensitive.

XML declaration is optional.


<?xml
version = "1.0/1.1"
encoding = "UTF-8"

© SSAENG 2009
My Note on Ajax page 13 of 21

standalone ="yes/no" ?>

There's no closing tag. standalone yes --> XML file has an internal DTD (document type definition).
no --> has a link to an external DTD

commenting: <!-- -->

XML elements with no content ("an empty element") can be written:


<element1></element1>
or
<element/>
An empty element can contain any number of attributes:
<element2 location="cityHall" phonenumber="055-261" />
These two attributes are separated by "one" blank space.

Types of elements (JavaScript properties that support XML DOM tree access). KNOWING WHICH
VALUES REPRESENT WHICH PROPERTIES IS ESSENTIAL.
Value property Description
1 NODE_ELEMENT Represents an element
2 NODE_ATTRIBUTE
3 NODE_TEXT
4 NODE_CDATA_SECTION
5 NODE_ENTITY_REFERENCE
6 NODE_ENTITY
7 NODE_PROCESSING_INSTRUCTION
8 NODE_COMMENT
9 NODE_DOCUMENT
10 NODE_DOCUMENT_TYPE
11 NODE_DOCUMENT_FRAGMENT
12 NODE_NOTATION

Verifying an XML file.


When loaded by web browsers, well-formed file will have no errors. If errors are found, the file must
be corrected before use.

XML Trees
When browsers load XML files, they automatically convert them into logical collections of related
nodes (generate a logical tree representation). A document element node contains a number of
subnodes. The subnodes are children of the document element and siblings to one another. Each of
these child nodes also has a child node (text node). of its own that contains text data.

Access XML DOM tree with JavaScript properties

© SSAENG 2009
My Note on Ajax page 14 of 21

(to interact, navigate, and extract data from XML files.)


Property Description
attributes Returns a list of attributes belonging to the node.
documentElement Returns a node's document element.
parentNode Returns a node's parent node.
childNodes Returns an array listing all of a node's child nodes.
firstChild Returns the first child belonging to a node.
lastChild Returns the last child belonging to a node.
name Returns a node's name.
localName Returns a node's local name.
nodeValue Returns a node's value.
nodeType Returns a node's type.
nodeName Return a node's name.
nextSibling Returns a node's next sibling (based on its order in the XML DOM tree)
previousSibling Returns a node's previous sibling (based on its order in the XML DOM
tree)

Navigating XML files


• write a function named getData() to navigate and extract the text content in a particular text node in
an XML file.
∘ start with instantiating of XMLHttpRequest
∘ use "GET" to download the "xml file" and assign a variable name to it.
∘ because some browsers (Firefox, Safari) interpret blank space in xml files as an empty text node
(W3C Standards), a function named "ClearOutWhiteSpace()" is used to eliminate white space.
‣ use a loop, with "if" to check the value of node's node type, if it is a text node (value =3), use a
regular expression and removeChild() method to remove the blank space.
∘ set up an object reference to the document element. Use properties "documentElement","firstChild",
"nextSibling".
• To get data, use the property, "nodeValue".

If an object contains one or more attributes, you can set up an object reference to those attributes using
the attributes property.

XML standard specification: http://www.w3.org/TR/REC-xml

JSON (JavaScript Object Notation)


• easy to learn
• use lists to access data
• drawback: Need to install a JSON library on the web server for many languages (PHP, Perl, Ruby, and
Java)

© SSAENG 2009
My Note on Ajax page 15 of 21

Design & steps


1. Create the application's XML files.
2. Create a new HTML page.
3. Get started on the application's JavaScript.
4. Set up an instance of an XMLHttpRequest object.
5. Develop the getXML() function.
6. Develop the ClearOutWhiteSpace() function.
7. Develop the checkAnswer() function.

CSS
• introduced in 1997, not a formal Ajax component, but it gives needed functionality.
• Advantages
∘ look and feel (color, size, font, layout, etc) will be consistency throughout a web page.
∘ help reduce the size of ajax applications (removing repetition simplify the script)
• basics of CSS syntax
∘ names of styles and values are specified by English keywords.
∘ style sheets consists of lists of rules
‣ Rules are comprised of one or more selectors and a declaration block
• a declaration block is comprised of a list of declarations.
• selectors are used to specify the elements to which styles are applied.
• common CSS properties
∘ font-family
∘ font-size
∘ font-stretch
∘ font-style
∘ font-weight
• common text formatting properties
∘ color
∘ text-align
∘ text-indent
∘ text-decoration
∘ line-height
∘ letter-spacing
∘ word-spacing
• common CSS color and background properties
∘ background-image (by specifying the image file url)
∘ background-color
∘ background-repeat
∘ background-position
• properties for positioning of element (Absolute positioning, use coordinates systems, the (0,0) is at
the top left corner, to specify a precise location. However, with different user's computer resolution,

© SSAENG 2009
My Note on Ajax page 16 of 21

size of coordinate system changes. Setting element's position to relative to other elements will ensure a
consistent look and feel. )
∘ top (value in pixel)
∘ bottom (value in pixel)
∘ left (value in pixel)
∘ right (value in pixel)
∘ position (absolute or relative)
∘ z-index (numeric value, when elements overlap one another)
• inline styles (CSS styles embedded in html tags)
• embedded styles (embed style rules inside the <style> and </style> tags., related rules are grouped
together. tag's id can be specified and referred. If the latter block with conflicting property would
override the former block.)
• external styles.
∘ move the declaration blocks from your <style> elements into an external file (without
<style></style> tags) and save with file name style.css
∘ use <Link rel="stylesheet" href="style.css"> in the html file (this reduces the size of file)

designing the application


1. assemble the application's external style sheet.
2. put together the application's external text file.
3. Create a new html page.
4. Start the application's JavaScript.
5. Develop the ProcessEvent () function.
6. Develop the getMouseData () function.
7. Develop the populateMenus () function.
8. Develop the RemoveMenus () function.
9. Develop the DisplayMenu () function.
10. Develop the ExecuteCommand () function.
11. Develop the StartPLay () function.
12. Develop the AnswerQuestion () function.
13. Develop the ResetScreen () function.

Ajax and PHP


PHP (hypertext preprocessor, 1995), an extremely popular server-based scripting language, is capable
of reading and writing files stored on web servers and working with database management systems.

Integrate PHP with html


Create a php file with html tags, and place the php statements within delimiter tags <?php and ?>
in the body section.

Store and retrieve data using variables and arrays


• "echo" (a little faster) and "print" can be used in php to Return data (text, or xml) back (see an

© SSAENG 2009
My Note on Ajax page 17 of 21

example):

<?php
header ('Content-Type: text/xml');
echo '<?xml version = "1.0" encoding="utf-8"?>';
echo '<dogs>; echo '<name>Sam</name>';
echo '<name>Miky</name>';
echo '</dogs>';
?>

Commenting with // or # and, for multi-line comments, with opening delimiter /* and closing delimiter
*/

PHP variables (beginning with "$" and the name:letters/numbers, or underscores) for storing data, an
example: $sum = 500;

PHP arrays for collections of data


example: an array named "$aDrinks"
$aDrinks[0] = "Coffee";
$aDrinks[1] = "Tea";
$aDrinks[2] = "CocaCola";

or,create using the array() function : $aDrinks = array("0" =>"Coffee", "1" => "Tea", "2" =>
"CocaCola");

accessing the array contents: echo "The second item stored in the array is: ". $aDrinks[1];

Note: PHP use "." as a concatenation operator to concatenate strings and use "+" to add numeric values
(While in JavaScript, the "+" is used to concatenate either numbers or strings.

PHP operators for assigning data: Examples


$x = 5; //x equals 5
$x = $x += 1; //x equals 6
$x = $x -= 1; //x equals 5
$x = $x *= 2; //x equals 10
$x = $x /= 2; //x equals 5

PHP arithmetic operators: Examples


$x = 5+1; //x equals 6
$x = $x-1; //x equals 5
$x = $x*5; //x equals 25
$x = $x/5; //x equals 5

© SSAENG 2009
My Note on Ajax page 18 of 21

$x++; //x equals 6


$x--; //x equals 6

PHP operators for comparing values.


== (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater
than or equal to)

PHP conditional logic


* if statement
* else statement
* else-if statement
* switch statement (To compare one value against a number of values)
• a ternary operator (alternative to conditional logic)
PHP's for loop has three parts: a variable declaration, a tested condition, and an increment/decrement
statement.

PHP's foreach loop


It automatically processes the contents of arrays and other collections of data without a need of
knowing the number of the elements.

PHP's while loop It repeats a collection of stements as long as a tested condition remains true.

PHP's "do...while" loop


It does not test its condition until the end of the loop. an example:
<?php
$ i= 5 ;
do {
echo $i . "<br>";
$i--;
} while ($i < 3);
?>
In the above example, it executes once and returns "5" as a result. Then, it decrements the value by 1
and tests the resulting value and stops the loop because of false.

PHP's "break" keyword to halt the loop and execute the following statement.

PHP's "continue" keyword to "skip" an iteration of a loop when certain situations occurs (No return for
the skipped value).

PHP's $_GET global array is used to access incoming arguments when the open() method's GET option
is used to pass data to a PHP script.

© SSAENG 2009
My Note on Ajax page 19 of 21

PHP's $_POST global array is used to access incoming arguments when the open() method's POST
option is used to pass data to a PHP script.

PHP: creating and accessing files:


fopen function syntax
fopen(filename, mode)

filename specifies the url of the file on the web server.

Mode Description
r read only
r+ read and write
w write only (if not existing, it's created.)
w+ read and write (if not existing, it's created.)
a append mode for writing (if not existing, it's created.)
a+ append mode for reading and writing (if not existing, it's created.)
X creates and opens a file for writing (if the specified file exists, a value of false is
returned.)
X+ creates and opens a file for reading and writing (if the specified file exists, a
value of "false" is returned.)

PHP: writing and reading files:


fwrite function: an example

<body>
<?php
$file = fopen(mybook.txt", "w");
$data = "This year term time will start sooner than the last term.";
$data = $data."Due to the nationwide long holidays at the end of the year.";
$data = $data."to provide students enough time to study.";
if (fwrite($file, $data) != true) {
echo "errors occurs, the file cannot be written";
}
fclose($file);
?>
</body>

Reading using a while loop (iterate line by line) until the end of file, and use the "fgets" method to
retrieve a line from a file and store it in a variable named $data, which is then displayed with "echo"
function.
<body>
<?php

© SSAENG 2009
My Note on Ajax page 20 of 21

$file = fopen(mybook.txt", "r");


while(!feof($file)){
$data = fgets($file);
echo $data."<br>";
}
fclose($file);
?>
</body>

Issues to think when designing an ajax application:


1. Some browsers do not support JavaScript, including <noscript> Alternative message </noscript> will
display this message to the user.
2. Ajax disables back & forward buttons.
3. In some cases, desktop applications are more preferable than ajax versions.
4. When making updates, do not make unexpected changes on the page, but rather make it easy to
identify by modifying its background or foreground colors.
5. Bookmark will not save the current state, but its initial state.
6. Lower the search engine relevancy ranking, because large amounts of content are remained on web
servers. To improve finding & indexing by spider, links maybe left on the HTML original page, or put a
link to a hypertext link sitemap, or provide a static version.
7. Dynamic updates are not always easily noticed. It should provide some type of visual indicator to
notify users. Examples:
document.getElementById("DivTrgt").style.color="blue";
or
document.getElementById("DivTrgt").style.background-color="yellow";
8. Instead of uploading user's information immediately to web server, the application should wait until
the form is completely filled and satisfied.
9. Test the ajax application with different browsers.
10. Do not build slow ajax applications. do not try to do all things that Ajax is capable of doing, but
use appropriate applications and request only needed data to run. (download too much data can impact
other network users by needlessly consuming network bandwidth.) Provide a visual indicator by using
an animated GIF file, like an hourglass file, to indicate that a download is in progress.
document.getElementById("ImgTrgt").style.visibility="visible";
Once the download is done,use:
if (Request.readyState == 4 && Request.status == 200) {
document.getElementById("ImgTrgt").style.visibility="hidden";
}
Other ways: changing the mouse pointer's appearance, popping up a dialog window message, or
displaying a message on browser's status bar.
11. Client-side JavaScript is easily viewable and therefore inherently insecure. The processing of
sensitive info (IDs/passwords) should be moved to web server and make sure that no such data makes it
way into JavaScript code.

© SSAENG 2009
My Note on Ajax page 21 of 21

12. do not overuse ajax


13. follow good programming practices. The comprehensive information regarding Ajax application
development practices is at http://www.ajaxpatterns.org

Internet Resources
http://en.wikipedia.org/wiki/HTML
http://www.w3.org/TR/html401
http://www.html.net/tutorials/html/introduction.asp
http://en.wikipedia.org/wiki/Document_Object_Model
http://www.w3.org/DOM
http://www.w3schools.com/HTMLDOM/default.asp
http://en.wikipedia.org/wiki/Xmlhttprequest
http://www.w3.org/TR/XMLHttpRequest
http://jibbering.com/2002/4/httprequest.html
http://en.wikipedia.org/wiki/Cascading_style_sheets
http://www.w3.org/Style/CSS
http://www.w3schools.com/Css/default.asp
http://en.wikipedia.org/wiki/Javascript
http://www.w3schools.com/JS/default.asp
http://en.wikipedia.org/wiki/Xml
http://en.wikibooks.org/wiki/XML
http://www.w3.org/XML
http://www.w3schools.com/xml/default.asp
http://en.wikipedia.org/wiki/Ajax
http://www.adaptivepath.com/ideas/essays/archives/000385.php
http://ajaxblog.com
http://ajaxian.com
http://www.ajax-blog.com

Test: Wrd Guessing http://www.thaibioinfo.org/tAja/WrdGuess/wrdGuessing.html

© SSAENG 2009

Das könnte Ihnen auch gefallen