Sie sind auf Seite 1von 53

1.

Introduction
JavaScript is a simple programming language that can be written directly into HTML documents to allow for increased interactivity with the user. For example, JavaScript can be used to create online calculators or show the current date and time.

2. Embedding JavaScript into your HTML document


Browsers that recognize JavaScript also recognize the special <SCRIPT> ... </SCRIPT> tag. This tag goes in the <HEAD> of your HTML document, along with your <TITLE> tag. Here's a short example:
<HTML> <HEAD> <TITLE>My JavaScript Page</TITLE> <SCRIPT> (JavaScript code goes in here) </SCRIPT> </HEAD> (rest of your HTML document goes here)

To make an object (such as an image, a form button, or a hyperlink) on your page do something in response to a user action, you can add an additional attribute to the tag for that object. For example, the following HTML snippet pops up a thank you message when the user clicks on the link:
<A HREF="http://www.cs.brown.edu/courses/bridge/" onClick="alert('Thanks for visiting the Bridge home page!')">Bridge home page</A>

Try it yourself! Just click on the following link: Bridge home page You're familiar with the HREF="" attribute that specifies the URL that the link points to, but note the additional onClick="" attribute. The stuff between those quotation marks is JavaScript code, which in this case pops up an alert box with the specified message. (Don't worry if you don't understand the stuff between the quotation marks; you'll learn it later on. The important thing right now is to understand the additional attribute.) Another point to recognize is that if a browser does not understand the <SCRIPT> tag, it will skip over it, and the text that is between the two tags (your code, basically) will appear on the screen as ordinary text. Since you want to create an HTML page that is viewable on all browsers, you would want to prevent this from happening.

To prevent this from happening, you should include the characters <!-- immediately following the <SCRIPT> tag and the characters --> immediately preceding the </SCRIPT> tag. In HTML in general, using this set of characters allows you to write comments to yourself that the browser will not read or display on the page. Inside the JavaScript tags, the browser ignores these characters. By doing this, a non-JavaScript readable browser will see the comment notation and ignore the text between them (which is your code). Your code would then look like this:
<HEAD> <SCRIPT> <!-(Your code goes here...) --> </SCRIPT> </HEAD>

3. Variables
3.1. What are Variables?
Variables are like storage units. You can create variables to hold values. It is ideal to name a variable something that is logical, so that you'll remember what you are using it for. For example, if you were writing a program to divide 2 numbers, it could be confusing if you called your variables numberOne, numberTwo, numberThree because you may forget which one is the divisor, which one is the dividend, and which one is the quotient. A more logical approach would be to name them just that: divisor, dividend, quotient. It is important to know the proper syntax to which variables must conform:

They must start with a letter or underscore ("_") Subsequent characters can also be digits (0-9) or letters (A-Z and/or a-z). Remember, JavaScript is case-sensitive. (That means that MyVariable and myVariable are two different names to JavaScript, because they have different capitalization.)

Some examples of legal names are Number_hits, temp99, and _name. When you declare a variable by assignment outside of a function, it is called a global variable, because it is available everywhere in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within the function. Using var is optional, but you need to use it if you have a variable that has been declared global and you want to re-declare it as a local variable inside a function. Variables can store all kinds of data (see below, Values of Variables, section 3.2). To assign a value to a variable, you use the following notation:

dividend = 8; divisor = 4; myString = "I may want to use this message multiple times"; message = myString;

Let's say the main part of the function will be dividing the dividend by the divisor and storing that number in a variable called quotient. I can write this line of code in my program: quotient = divisor*dividend, and I have both stored the value of the quotient to the variable quotient and I have declared the variable at the same time. If I had wanted to, I could have declared it along with my other assigned variables above, with a value of null. After executing the program, the value of quotient will be 2.

It is important to think about the design of your program before you begin. You should create the appropriate variables so that it makes your life easier when you go to write the program. For instance, if you know that you will be coding a lot of the same strings in a message, you may want to create a variable called message and give it the value of your message. That way, when you call it in your program, you do not have to retype the same sentence over and over again, and if you want to change the content of that message, you only have to change it once -- in the variable declaration.

3.2. Values of Variables


JavaScript recognizes the following types of values:

Numbers, such as 42 or 3.14159 Logical (Boolean) values, either true or false Strings, such as "Howdy!" null, a special keyword which refers to nothing

This relatively small set of types of values, or data types, enables you to perform useful functions with your applications. There is no explicit distinction between integer and real-valued numbers.

3.3. Data Type Conversion


JavaScript is a loosely typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:
var answer = 42

And later, you could assign the same variable a string value, for example,
answer = "Thanks for all the fish..."

Because JavaScript is loosely typed, this assignment does not cause an error message. However, this is not good coding! You should create variables for a specific type, such as an integer, string, or array, and be consistent in the values that you store in the variable. This prevents confusion when you are writing your program. In expressions involving numeric and string values, JavaScript converts the numeric values to strings. For example, consider the following statements:
x = "The answer is " + 42 y = 42 + " is the answer."

(The + sign tells JavaScript to concatenate, or stick together, the two strings. For example, if you write:
message = "Hello" + "World"

...then the variable message becomes the string "Hello World") In the first statement, x becomes the string "The answer is 42." In the second, y becomes the string "42 is the answer."

4. Literals
You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. Examples of literals include: 1234, "This is a literal," and true.

4.1. Integers
Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7. Some examples of integer literals are: 42, 0xFFF, and -345.

4.2. Floating-point literals


A floating-point literal can have the following parts: a decimal integer, a decimal point ("."), a fraction (another decimal number), an exponent, and a type suffix. The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit, plus either a decimal point or "e" (or "E"). Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12

4.3. Boolean literals

The Boolean type has two literal values: true and false.

4.4. String literals


A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or double quotation marks. The following are examples of string literals:

"blah" 'blah' "1234" "one line \n another line"

In addition to ordinary characters, you can also include special characters in strings, as shown in the last element in the preceding list. The following table lists the special characters that you can use in JavaScript strings.
Character \b \f \n \r \t \\ Meaning backspace form feed new line carriage return tab backslash character

4.5. Escaping characters


For characters not listed in the preceding table, a preceding backslash is ignored, with the exception of a quotation mark and the backslash character itself. You can insert quotation marks inside strings by preceding them with a backslash. This is known as escaping the quotation marks. For example,
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service." document.write(quote)

The result of this would be

He read "The Cremation of Sam McGee" by R.W. Service.

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:
var home = "c:\\temp"

5. Arrays
An Array is an object which stores multiple values and has various properties. When you declare an array, you must declare the name of it, and then how many values it will need to store. It is important to realize that each value is stored in one of the elements of the array, and these elements start at 0. This means that the first value in the array is really in the 0 element, and the second number is really in the first element. So for example, if I want to store 10 values in my array, the storage elements would range from 0-9. The notation for declaring an array looks like this:
myArray = new Array(10); foo = new Array(5);

Initially, all values are set to null. The notation for assigning values to each unit within the array looks like this:
myArray[0] = 56; myArray[1] = 23; myArray[9] = 44;

By putting the element number in brackets [ ] after the array's name, you can assign a value to that specific element. Note that there is no such element, in this example, as myArray[10]. Remember, the elements begin at myArray[0] and go up to myArray[9]. In JavaScript, however, an array's length increases if you assign a value to an element higher than the current length of the array. The following code creates an array of length zero, then assigns a value to element 99. This changes the length of the array to 100.
colors = new Array(); colors[99] = "midnightblue";

Be careful to reference the right cells, and make sure to reference them properly! Because arrays are objects, they have certain properties that are pre-defined for your convenience. For example, you can find out how many elements myArray has and store this value in a variable called numberOfElements by using:
numberOfElements = myArray.length;

6. Operators
JavaScript has many different operators, which come in several flavors, including binary. This tutorial will cover some of the most essential assignment, comparison, arithmetic and logical operators.

6.1. Selected assignment operators


An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. The other operators are shorthand for standard operations. Find an abridged list of shorthand operators below:
Shorthand operator Meaning x += y x -= y x *= y x /= y x=x+y x=x-y x=x*y x=x/y

Note that the = sign here refers to assignment, not "equals" in the mathematical sense. So if x is 5 and y is 7, x = x + y is not a valid mathematical expression, but it works in JavaScript. It makes x the value of x + y (12 in this case). EXAMPLES: If x = 10 and y = 2, x += y would mean x = x + y, hence x's new value would be the sum of x's previous value plus y's previous value. Upon executing x = x + y = 10 + 2, x's new value becomes 12, while y's new value remains equal to its old value. Similarly, x -= y would change x's value to 8. Calculate x *= y and x /= y to get a better idea of how these operators work.

6.2. Comparison operators


A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands can be numerical or string values. When used on string values, the comparisons are based on the standard lexicographical ordering. They are described in the following table.
Operator Description Example

Equal (= =)

Evaluates to true if the operands are equal. Evaluates to true if the operands are not equal. Evaluates to true if left operand is greater than right operand. Evaluates to true if left operand is greater than or equal to right operand.

x == y evaluates to true if x equals y. x != y evaluates to true if x is not equal to y. x > y evaluates to true if x is greater than y. x >= y evaluates to true if x is greater than or equal to y.

Not equal (!=)

Greater than (>) Greater than or equal (>=) Less than (<) Less than or equal (<=)

Evaluates to true if left operand is less than x < y evaluates to true if x is less right operand. than y. Evaluates to true if left operand is less than x <= y evaluates to true if x is less or equal to right operand. than or equal to y.

EXAMPLES: 5 == 5 would return TRUE. 5 != 5 would return FALSE. (The statement 'Five is not equal to five.' is patently false.) 5 <= 5 would return TRUE. (Five is less than or equal to five. More precisely, it's exactly equal to five, but JavaScript could care less about boring details like that.)

6.3. Selected Arithmetic Operators


Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/) and remainder (%). These operators work as they do in other programming languages, as well as in standard algebra. Since programmers frequently need to add or subtract 1 from a variable, JavaScript has shortcuts for doing this. myVar++ adds one to the value of myVar, while myVar-subtracts one from myVar. EXAMPLES: Let x = 3. x++ bumps x up to 4, while x-- makes x equal to 2.

6.4. Logical Operators


Logical operators take Boolean (logical) values as operands and return a Boolean value. That is, they evaluate whether each subexpression within a Boolean expression is true or false, and then execute the operation on the respective truth values. Consider the following table:

Operator Usage and (&&) expr1 && expr2 expr1 || expr2 !expr

Description True if both logical expressions expr1 and expr2 are true. False otherwise. True if either logical expression expr1 or expr2 is true. False if both expr1 and expr2 are false. False if expr is true; true if expr is false.

or (||) not (!)

EXAMPLES: Since we have now learned to use the essential operators, we can use them in conjunction with one another. See if you can work out why the following examples resolve the way they do: If x = 4 and y = 7, ((x + y + 2) == 13) && (((x + y) / 2) == 2) returns FALSE. If x = 4 and y = 7, ((y - x + 9) == 12) || ((x * y) == 2) returns TRUE. If x = 4 and y = 7, !((x/2 + y) == 9) || ((x * (y/2)) == 2) returns FALSE.

7. Using JavaScript Objects


When you load a document in your web browser, it creates a number of JavaScript objects with properties and capabilities based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself. The pre-defined objects that are most commonly used are the window and document objects. The window has methods that allow you to create new windows with the open() and close() methods. It also allows you to create message boxes using alert(), confirm(), and prompt(). Each displays the text that you put between the parentheses. For example, the following code:
alert("This is an alert box")

...pops up an alert box displaying the given message. Try it yourself by clicking on this link. The document object models the HTML page. The document object contains arrays which store all the components constituting the contents of your web page, such as images, links, and forms. You can access and call methods on these elements of your web page through the arrays.

The objects in this pre-defined hierarchy can be accessed and modified. To refer to specific properties, you must specify the property name and all its ancestors, spelling out the complete hierarchy until the document object. A period, '.', is used in between each object and the name of its property. Generally, a property / object gets its name from the NAME attribute of the HTML tag. For example, the following refers to the value property of a text field named text1 in a form named myform in the current document.
document.myform.text1.value

Form elements can also be accessed through the aforementioned forms array of the document object. In the above example, if the form named myform was the first form on the page, and text1 was the third field in the form, the following also refers to that field's value property.
document.forms[0].elements[2].value

Functions (capabiltiies) of an object can similarly be accessed using the period notation. For example, the following instruction resets the 2nd form in the document.
document.forms[2].reset();

Click on one of the objects below to view the Netscape documentation on the specific properties and methods that that object has:

8. Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure -- a set of statements that performs a specific task. A function definition has these basic parts:

The function keyword A function name A comma-separated list of arguments to the function in parentheses The statements in the function in curly braces: { }

8.1. Defining a Function


When defining a function, it is very important that you pay close attention to the syntax. Unlike HTML, JavaScript is case sensitive, and it is very important to remember to enclose a function within curly braces { }, separate parameters with commas, and use a semi-colon at the end of your line of code. It's important to understand the difference between defining and calling a function. Defining the function names the function and specifies what to do when the function is called. You define a function within the <SCRIPT>...</SCRIPT> tags within the <HEAD>...</HEAD> tags. In defining a function, you must also declare the variables which you will be calling in that function. Here's an example of defining a function:
function popupalert() { alert('This is an alert box.'); }

Notice the parentheses after the function name. It is imperative that you include these parentheses, even if they are empty. If you want to pass a parameter into the function, you would include that parameter inside of the parentheses. A parameter is a bit of extra information that cn be different each time the function is run. It is stored in a variable and can be accessed just like any other variable. Here's an example of a function that takes a parameter:
function anotherAlert(word) { alert(word + ' is the word that you clicked on'); }

When you call this function, you need to pass a parameter (such as the word that the user clicked on) into the function. Then the function can use this information. You can pass in a different word as a parameter each time you call the function, and the alert box will change appropriately. You'll see how to pass a parameter a little later on.

You can pass in multiple parameters, by separating them with a comma. You would want to pass in a few parameters if you have more than one variable that you either want to change or use in your function. Here are two examples of passing in multiple parameters when you are defining the function:
function secondAlert(word,password) { confirm(word + ' is the word that you clicked on. The secret password is ' + password); }

function thirdAlert(word,password) { confirm(word + ' is the word you clicked on. Please take note of the password, ' + password); }

You'll notice that the same parameters are passed into both of these functions. However, you can pass in whatever values you want to use (see this same example below in calling the function).

8.2. Calling a Function


Calling the function actually performs the specified actions. When you call a function, this is usually within the BODY of the HTML page, and you usually pass a parameter into the function. A parameter is a variable from outside of the defined function on which the function will act. Here's an example of calling the same function:
popupalert();

For the other example, this is how you may call it:
<A HREF="#top" onClick="anotherAlert('top')">top</A>

This would bring you to the top of the page, and bring up an alert box that said: "top is the word you clicked on" Try it for yourself: top Here is the same example with multiple parameters that was shown above:
<A HREF="#top" onClick="secondAlert('awesome','pandas')">awesome</A> <A HREF="#top" onClick="thirdAlert('computers','insert')">computers</A>

You'll notice in the code that different values for the variables word and password are passed in. These values here are what the function will need to perform the actions in the function. Make sure that the values you pass in are in the correct order because the function will take them in and assign these values to the parameters in the parentheses of the function declaration. Once you pass values into your function, you can use them however you want within your function. Try it for yourself: When you click on the words below, a confirmation box will pop up and then the link will bring you to the top of the page. awesome computers

9. If/Else Statements
if statements execute a set of commands if a specified condition is true. If the condition is

false, another set of statements can be executed through the use of the else keyword.

The main idea behind if statements is embodied by the sentence: "If the weather's good tomorrow, we'll go out and have a picnic and Lisa will do cartwheels -- else, we'll stay in and Catherine will watch TV." As you can see, the idea is quite intuitive and, surprisingly enough, so is the syntax:
if (condition) { statements1 }

-orif (condition) { statements1

} else { statements2 }

(An if statement does not require an else statement following it, but an else statement must be preceded by an if statement.) condition can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If condition evaluates to true, the statements in statements1 are executed. statements1 and statements2 can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in braces. Here's an example:
if (weather == 'good') { go_out(we); have_a_picnic(we); do_cartwheels(Lisa); } else { stay_in(we); watch_TV(Catherine); }

10. Loops
Loops are an incredibly useful programming tool. Loops handle repetitive tasks extremely well, especially in the context of consecutive elements. Arrays immediately spring too mind here, since array elements are numbered consecutively. It would be quite intuitive (and equally practical), for instance, to write a loop that added 1 to each element within an array. Don't worry if this doesn't make a lot of sense now, it will, after you finish reading the tutorial. The two most common types of loops are for and while loops:

10.1. for Loops


A for loop constitutes a statement which consists of three expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop. This definition may, at first, sound confusing. Indeed, it is hard to understand for loops without seeing them in action. A for loop resembles the following:

for (initial-expression; condition; increment-expression) { statements }

The initial-expression is a statement or variable declaration. (See the section on variables for more information.) It is typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. The condition is evaluated on each pass through the loop. If this condition evaluates to true, the statements in statements are performed. When the condition evaluates to false, the execution of the for loop stops. This conditional test is optional. If omitted, the condition always evaluates to true. The increment-expression is generally used to update or increment the counter variable. The statements constitute a block of statements that are executed as long as condition evaluates to true. This can be a single statement or multiple statements. Although not required, it is good practice to indent these statements from the beginning of the for statement to make your code more readable. Check out the following for statement. It starts by declaring the variable i and initializing it to zero. It checks whether i is less than nine, performs the two successive statements, and increments i by one after each pass through the loop:
var n = 0; for (var i = 0; i < 3; i++) { n += i; alert("The value of n is now " + n); }

Try it yourself: Click this link

10.2. while Loops


The while loop, although most people would not recognize it as such, is for's twin. The two can fill in for one another - using either one is only a matter of convenience or preference according to context. while creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true.

The syntax of while differs slightly from that of for:


while (condition) { statements }

condition is evaluated before each pass through the loop. If this condition evaluates to true, the statements in the succeeding block are performed. When condition evaluates to false, execution continues with the statement following statements.

statements is a block of statements that are executed as long as the condition evaluates to true. Although not required, it is good practice to indent these statements from the beginning of the statement. The following while loop iterates as long as n is less than three.
var n = 0; var x = 0; while(n < 3) { n++; x += n; alert("The value of n is " + n + ". The value of x is " + x); }

Try it for yourself: Click this link

11. Commenting
Comments allow you to write notes to yourself within your program. These are important because they allow someone to browse your code and understand what the various functions do or what your variables represent. Comments also allow you to understand your code if it's been a while since you last looked at it.

In JavaScript, you can write both one-line comments and multiple line comments. The notation for each is different though. For a one line comment, you precede your comment with //. This indicates that everything written on that line, after the //, is a comment and the program should disregard it. For a multiple-line comment, you start with /* and end with */ . It is nice to put an * at the beginning of each line just so someone perusing your code realizes that he/she is looking at a comment (if it is really long this helps). This is not necessary though. The following are examples of comments in JavaScript.
// This is a single line comment. /* This is a multiple line comment with only one line. */ /* This is a multiple line comment. * The star (*) at the beginning of this line is optional. * So is the star at the beginning of this line. */ Dojo Toolkit is a JavaScript Framework that allows you to easily create AJAX driven applications on the web. The API is very straight forward and Dojo is one of the most widespread and functional JavaScript frameworks. You can call AJAX functions using XhrGet and XhrPost (though there are others).

Using Dojo JavaScript Framework

You can instantly include Dojo in your project without even downloading anything, since it's already hosted by Google. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" djConfig="parseOnLoad: false"></script> djConfig is a quick way to configure a few options as dojo is loaded. If you have for example: djConfig="parseOnLoad: true" this means that dojo.parser will be automatically loaded. the dojo parser exists to parse any dojoType attributes in your XHTML. If you set djConfig="parseOnLoad: false" then you must do this: <script type="text/javascript" djConfig="parseOnLoad:false" src="dojo/dojo.js"></script> <script type="text/javascript"> dojo.require("dojo.parser"); dojo.addOnLoad(function(){ dojo.parser.parse(); }); </script> Since we don't have any dijit elements or dojoType attributes, we can keep the parseOnLoad false.

AJAX GIF Loading Image


First, I designed some images to use as my loading graphic, in case the load takes too long. Feel free to use them in your AJAX applications:

The JavaScript
Next, I use the addOnLoad function: <script type="text/javascript"> dojo.addOnLoad(function() { dojo.query("#ajax_button").onclick(function(e) { var node = e.target;

Using the dojo class, I addOnLoad which will run as soon as the page loads. The query function is similar to jQuery ( $ function ) to load a specific CSS class, currently it's the class of my button. Variable node can be used to modify the button itself. Keep this script tag open, we'll continue it below.

The XHTML form


First, let's create some XHTML so you can see what the form will look like: <body class=" tundra"><div id="dojo"> <!-- content --> <form id="dojo_ajax"> <br /> <button type="button" name="ajax_button" id="ajax_button">Fetch Articles</button> <div id="dojo_ajax_response"></div> </form> </div></body>

When the user presses the Fetch Articles button, we'll XMLHttpRequest a JSON file that has 5 articles with links.

Preload Loading GIF Image


Continuing right below the JavaScript we made earlier, let's preload the loading image. var dojo_table = dojo.byId('dojo_ajax_response'); var rimg = new Image(); rimg.src = "loading.gif"; dojo_table.innerHTML = "<br /><br /><br /><img src='loading.gif' alt='loading' />";

Variable dojo_table will be the div that displays our results from the AJAX request. rimg = new Image() is a simple way to pre-load a graphic before we put in the XHTML. We insert the loading graphic into the dojo_table because someone clicked our AJAX button.

The AJAX Code


We finally call dojo.xhrGet to make an AJAX GET request. For the arguments we use a plaintext document with JSON formatted data inside to use as our source data. We handle it as text because it's a text file. Time out in 5 seconds if we cannot find the file.

Important Note: Remember, you cannot fetch data from a different domain than the one your script is on, for the argument "url"--this is because of cross-browser security that is implemented in your browser. To get data from a different website, you must use PHP cURL or some other proxy server language to fetch the data. For example, if I have a code that grabs a CNN feed, such as MyCNNfeed.php, then I would use that as the url argument. If the feed is in JSON, I make "HandleAs" JSON (application/JSON), or maybe it will be XML, so HandleAs XML. Load argument is a function that gets called when the AJAX call is finished. dojo.xhrGet({ url: "file:///C:/Dojo/json.txt", // fetch this data handleAs:"text", // since we use a plaintext document... timeout: 5000, // give up after 5 seconds load: function(data, ioArgs){ // ioArgs is loaded with XHR information, but not useful in simple cases // data is the response from the form's action="" url var obj = {}; obj = JSON.parse(data); var s = "<h1>Stories</h1><ol>"; for(var i = 0; i < obj.numstories; i++){ s += '<li><a href="'+obj.stories[i].url+'">'+obj.stories[i].title+'</a></li>'; } s += '</ol>'; dojo_table.innerHTML = s; }, error: function(err, ioArgs){ // again, ioArgs is useful, but not in simple cases dojo_table.innerHTML = "An unexpected error occurred: " + error; } }); }, 1000); }); </script> In the load function, we parse the JSON data and turn it into a JavaScript object. We make a string called s and fill it with our data in list form. We set the dojo_table innerHTML to display the data (in the process deleting the loading image). Error function will be loaded if a problem occurs. Here's the JSON file I used, it's very simple and self-explanatory:

{ "numstories": "stories": [ {"title": {"title": {"title": {"title": {"title": ] }

5, "a", "b", "c", "d", "e", "url": "url": "url": "url": "url": "http://"}, "http://"}, "http://"}, "http://"}, "http://"}

The Full Code


For your convenience I've added the full code for you to test immediately. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head><meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <meta name="author" content="InfernoDevelopment.com" /> <!-- metadata --> <title>Dojo Ajax XHR Example</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" djConfig="parseOnLoad: false"></script> <script type="text/javascript"> dojo.addOnLoad(function() { dojo.query("#ajax_button").onclick(function(e) { var node = e.target; var dojo_table = dojo.byId('dojo_ajax_response'); var rimg = new Image(); rimg.src = "loading.gif"; dojo_table.innerHTML = "<br /><br /><br /><img src='loading.gif' alt='loading' />"; dojo.xhrGet({ url: "file:///C:/Dojo/json.txt", // read the url: from the action="" of the <form> handleAs:"text", timeout: 5000, // give up after 5 seconds load: function(data, ioArgs){ // ioArgs is loaded with XHR information, but not useful in simple cases // data is the response from the form's action="" url var obj = {}; obj = JSON.parse(data); var s = "<h1>Stories</h1><ol>"; for(var i = 0; i < obj.numstories; i++){ s += '<li><a href="'+obj.stories[i].url+'">'+obj.stories[i].title+'</a></li>';

} s += '</ol>'; dojo_table.innerHTML = s; }, error: function(err, ioArgs){ // again, ioArgs is useful, but not in simple cases dojo_table.innerHTML = "An unexpected error occurred: " + error; } }); }, 1000); }); </script> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.4/dijit/themes/tundra/tundr a.css" /> </head><body class=" tundra"><div id="dojo"> <!-- content --> <form id="dojo_ajax"> <br /> <button type="button" name="ajax_button" id="ajax_button">Fetch Articles</button> <div id="dojo_ajax_response"></div> </form> </div></body></html>

Other AJAX Features


There are other AJAX functions such as XhrPost to send POST data. You can use the "content" argument in the form of: content: { part:"one", another:"part" } // creates ?part=one&another=part with GET, Sent as POST data when using xhrPost You can use the form argument to define a form and grab the action url from that. There is also XhrPut and XhrDelete for those kinds of HTTP requests.

1. Ajax - Asynchronous JavaScript and XML


1.1. Overview
Ajax (Asynchronous JavaScript and XML) describes the possibility to communicate with the webserver in the background and to update a webpage with information from the webserver without re-loading the webpage.

Ajax can improve the usability of a webpage, e.g. a webpage can quickly be displayed while information is still loaded from the webserver. Ajax is based on the XMLHttpRequest and is considered to by a key technology to realize Web 2.0. For details on the XMLHttpRequest please see the resource section of this article.

1.2. Introduction to JavaScript


This article assume some familiarity with JavaScript. Please see Javascript - Tutorial for a introduction into JavaScript.

2. Installing Dojo
Download the "Dojo Toolkit" from http://dojotoolkit.org/ and extract the zip file. As of the time of writing this article the release of dojo is version 1.3.1. Rename the name directory to "dojoroot". Put this directory into a folder "web".

I recommend that you use the proposed folder names, this makes it easier to follow this tutorial.

The folder structure should look like the following.

3. Eclipse
The following examples work without Eclipse but Eclipse provides nice editors for html pages and css style sheets. If you want you can use Eclipse Eclipse installation . If you want to use Eclipse for the following examples, create a general project "de.vogella.dojo.client" via File-> New -> Project -> General -> Project. Create a folder "web" in this project and copy "dojoroot" in the folder "web". The following will refer always to the folder "web". If you are using Eclipse use your project, otherwise use the file structure.

4. Your first Dojo pages


4.1. Table handling
In your directory "web" create a table.html file with the following content.

The following uses the dojo cascading style sheets (css). If you want to overwrite any of these style can assume that you also include another style sheet after the dojo css include and overwrite any style you like.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script type="text/javascript" src="dojoroot/dojo/dojo.js" djConfig="parseOnLoad: true, isDebug: false"></script>

<script language="JavaScript" type="text/javascript"> dojo.require("dijit.TitlePane"); dojo.require("dojo.parser"); </script>

<style type="text/css"> @import "dojoroot/dijit/themes/tundra/tundra.css"; </style> </head> <body class="tundra">

<div dojoType="dijit.TitlePane" title="Title is displayed" style="width: 300px;"> Cool context </div> </body> </html>

Load the created webpage in a browser. You get a table with can be minimized and maximized again. This example shows the same table but is closed per default

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script type="text/javascript" src="dojoroot/dojo/dojo.js" djConfig="parseOnLoad: true, isDebug: false"></script>

<script language="JavaScript" type="text/javascript"> dojo.require("dijit.TitlePane"); dojo.require("dojo.parser"); </script>

<style type="text/css"> @import "dojoroot/dijit/themes/tundra/tundra.css";

</style> </head> <body class="tundra"> <div dojoType="dijit.TitlePane" title="This Title is closed by default" open="false" style="width: 300px;"> Context is at loading time not visible </div> </body>

</html>

4.2. Tooltip
This HTML file uses a tooltip on one element.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Dojo Tooltip Widget Test</title>

<style type="text/css"> @import "./dojoroot/dijit/themes/tundra/tundra.css"; @import "./dojoroot/dojo/resources/dojo.css"

</style>

<script type="text/javascript" src="./dojoroot/dojo/dojo.js" djConfig="parseOnLoad: true, isDebug: false"></script>

<script type="text/javascript"> dojo.require("dijit.Tooltip"); </script>

</head> <body class="tundra"> <span id="s1">s1 text</span><br><br><br>

<span dojoType="dijit.Tooltip" connectId="s1">s1 tooltip</span>

</body> </html>

5. Accessing the server


5.1. Reading a fixed file from a server
Dojo allows you to read data from the server. The following HTML page will connect the server and asynchronously load the content from the web server. In this example the loaded content is a static text page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script type="text/javascript" src="dojoroot/dojo/dojo.js" djConfig="parseOnLoad: true, isDebug: false"> </script>

<script type="text/javascript"> function readFile() { // dojo.xhrGet( { // // The following URL must match that used to test the server. url: "http://www.vogella.de/articles/AjaxwithDojo/download/includeTextFile.txt", handleAs: "text",

timeout: 5000, // Time in milliseconds

// The LOAD function will be called on a successful response. load: function(response, ioArgs) { // dojo.byId("replace").innerHTML = response; // return response; // },

// The ERROR function will be called in an error case.

error: function(response, ioArgs) { // console.error("HTTP status code: ", ioArgs.xhr.status); // dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; // return response; // } }); } </script> <script type="text/javascript"> dojo.addOnLoad(readFile); </script> </head> <body> <div id="replace" style="font-size: big"></div> </body> </html>

This example may not be running on a local file system. If you do not see something try to replace the URL http://www.vogella.de/articles/AjaxwithDojo/download/includeTextFile.txt with a path to a local file. This should then also work with a local running HTML page.

Start the HTML. The Dojo javascript will access the text file in the background and update the webpage with the information once the text file is read. Welcome to the world of Ajax! You successfully loaded a content from a website and included the response into your existing HTML page.

5.2. Send data to the server and update the page with the response

Now you need a build a server side application. I'm going to use Java Servlets for this but you can use any other language on the server you like, e.g. Perl, PHP, etc. Create the following Java servlet, compile it and deploy it to your server. I'm going to assume that the servlet will be running on the URL yourhomepage/servlets/ReturnParameters.

package testing;

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

/** * Servlet implementation class for Servlet: ReturnParameters * */ public class ReturnParameters extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L;

/* * (non-Java-doc) *

* @see javax.servlet.http.HttpServlet#HttpServlet() */ public ReturnParameters() { super(); }

/* * (non-Java-doc) * * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, * */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpServletResponse response)

String url = ""; String name = ""; boolean check = true; url = request.getParameter("url"); name = request.getParameter("name"); if (url==null|| name == null){ check=false; } response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<head><title>Response</title>"); if (check == false) { out.println("Missing Parameters"); } else { out.println("You name is " + name + " and the supplied URL is " + url + "."); } out.println("</head>"); out.println(""); } }

Now create the following HTML page which calls the servlet with two parameters and displays the result at a certain place in the application.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html> <head> <script type="text/javascript" src="dojoroot/dojo/dojo.js" djConfig="parseOnLoad: true, isDebug: false">

</script> <script type="text/javascript"> function readFile() { // dojo.xhrGet( { // The following URL must match that used to test the server. url: "http://www.jnerlich.de/servlets/ReturnParameters", handleAs: "text", timeout: 5000, // Time in milliseconds

// The LOAD function will be called on a successful response. load: function(response, ioArgs) { // // Search for the HTML tag with the ID "replace" and replace it with the answer of // of the servlet call dojo.byId("replace").innerHTML = response; // return response; // },

// The ERROR function will be called in an error case. error: function(response, ioArgs) { // console.error("HTTP status code: ", ioArgs.xhr.status); // dojo.byId("replace").innerHTML = 'Loading the ressource from the server did not work'; // return response; // },

// Here you put the parameters to the server side program // We send two hard-coded parameters content: {name: "lars", url:"testing" } }); } </script>

<script type="text/javascript"> dojo.addOnLoad(readFile); </script> </head> <body>

<!--This is the tag which will be replaced by the AJAX call <div id="replace" style="font-size: big"></div>

-->

</body>

</html>

Struts 2 AJAX Tutorial Dojo Autocompleter Example

This tutorial was written for Struts 2.1.2. A lot has changed in newer versions. The Dojo Plugin is no longer officially supported by the Struts 2 team. Also, please see Muhammads comment in

the comment section if youre using the latest version of Struts 2. You may want to check out Google Closure if youre looking for a good JS library. Struts 2 comes with a Dojo Toolkit plugin which makes developing an AJAX application easier than ever. In addition, the AJAX plugin I would most recommend is the Struts 2 JSON plugin. In this example, we will use the two side-by-side to create an autocompleter. In order to use the Ajax support provided in Struts 2, I would recommend Struts 2.1.2 or later. Include struts2-dojo-plugin-2.1.2.jar and jsonplugin-0.30.jar in your WEB-INF/lib directory. First, we will create the action for the field that we wish to autocomplete:
package com.lumidant.tutorial.struts2.action; import java.util.HashMap; import java.util.Map; import com.opensymphony.xwork2.ActionSupport; import com.lumidant.tutorial.struts.dao.*; public class AutocompleteField extends ActionSupport { private String city; private Map<String,String> json; public String execute() throws Exception() { return SUCCESS; } public String getCities() throws Exception() { json = new HashMap<String,String>(); if(city != null && city.length() > 0) { CityDao dao = new CityDao(); List<City> cities = dao.getCitiesStartingWith(city); for(City city : cities) { json.put(city.getId(), city.getName() + ", " + city.getState().getAbbreviation()); } } return SUCCESS; } public void setCity(String city) { this.city = city; } public Map<String,String> getJson() { return json; } }

The getCities method in our action acts on the input String city that were given and creates a Map of cities starting with that text. The key of our Map is going to be the hidden option value while the value of our Map is going to be our option text. Next, we will modify our struts.xml configuration file to utilize the JSON plugin by extending json-default:
<package name="example" extends="json-default"> <action name="AutocompleteField" class="com.lumidant.tutorial.struts2.action.AutocompleteField"> <result type="json><param name="root">json</param></result> </action> </package>

The root parameter that we specify is the name of the variable from our Action that we want to have converted and serialized to a JSON output. If instead of serializing a Java object to JSON you wish to create the JSON string directly yourself, you can instead use a result type of stream:
<action name="jsondata" class="com.lumidant.tutorial.struts2.action.JsonDataAction"> <result type="stream"> <param name="contentType">application/json</param> </result> </action>

And finally, we get to create our .jsp view:


<%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib prefix="sx" uri="/struts-dojo-tags" %> <html> <head> <sx:head /> </head> <body> <s:url id="cityList" action="AutocompleteField" method="getCities" /> <sx:autocompleter name="city" theme="ajax" href="%{cityList}" size="24" /> </body> </html>

For any of the Dojo plug-in features that you use, you will need to include the <sx:head /> tag, which includes the relevant JavaScript tags into your pages head tag. Then you can see that the autocompleters name attribute aligns with the city field in our Action and the urls method attribute aligns with our Actions getCities method. Now, when you visit your new page and start typing in the text box, you should see the field autocompleting. There are some other cool built-in Dojo tags that you should look at as well like the datetimepicker, which provides a really nice calendar.

Ajax Frameworks
In this lesson of the Ajax tutorial, you will learn... 1. 2. 3. 4. About the benefits of Ajax Frameworks. How to use the Dojo framework to make XMLHttpRequests. How to use the Prototype framework to make XMLHttpRequests. About some other popular frameworks.

The Purpose of Frameworks


JavaScript frameworks can serve several purposes:

Abstraction. Writing JavaScript is notoriously difficult in large part because of the browser and platform differences. Although this has improved a lot since the Netscape 4 / IE 4 days, JavaScript developers still have to be aware of differences in browser object models. One purpose of frameworks is to abstract those differences. Widget Libraries. Many frameworks provide libraries of pre-written, customizable widgets (expandable trees, accordions, autocompletes, drag-and-drop controls, etc.). Development Structure. Some frameworks make it easier to create structured, object-oriented Ajax applications.

Choosing a Framework
Choosing a framework to use for your Ajax applications is a difficult task. At the time of this writing, the AjaxPatterns website (http://ajaxpatterns.org/Ajax_Frameworks) listed:

30 multi-purpose Ajax frameworks 32 Java-specific Ajax frameworks 27 PHP-specific Ajax frameworks 15 .NET-specific Ajax frameworks

Many of these frameworks are created by individuals or small groups and most are noncommercial. So how do you choose? It's a tough job, but here are some general guidelines.
1. Choose a framework with staying power. The more mature frameworks like Prototype and Dojo, which we will review shortly, have built up pretty large followings, so they are more likely to persist. They are also more likely to be better documented and supported by an online community. 2. Choose a framework that is either language neutral or specific to your server-side language. This is pretty obvious, but you don't want a PHP framework if you are building a Java application. 3. Choose a framework that plays nicely with other frameworks. For example, script.aculo.us (see footnote) and Rico (see footnote) both require Prototype, so if you want to use some of their cool dynamic features, you will have to use Prototype as well. 4. Choose a framework that fits your skillset. If your developers are very comfortable with JavaScript, you might choose a framework that is JavaScript-centric like Prototype or Dojo. If you

are a team of Java or JSP developers who have not done much client-side programming, you might choose a framework like AjaxAnywhere (see footnote), which autogenerates the JavaScript. Such frameworks provide less flexibility but may decrease development time.

We will look at two popular frameworks: Dojo and Prototype. Note that these frameworks have a much broader focus than Ajax, but for now, we'll be focusing on how they handle XMLHttpRequests.

Dojo (see footnote)


Dojo is a multi-purpose JavaScript toolkit that, according to its website, "allows you to easily build dynamic capabilities into web pages and any other environment that supports JavaScript sanely." Dojo has been in development since late 2004 and is one of the most comprehensive JavaScript toolkits available. It is client-side specific so it can be used on any platform with any server-side language. The documentation for Dojo is relatively good compared with other frameworks.

Downloading Dojo
The latest version of Dojo is freely available for download at http://dojotoolkit.org/downloads as an archived file. Simply extract the files to a folder on your web server. (see footnote) Version 1.1 of Dojo is included with your class files (/dojo/dojo.js). Note that dojo.js has several dependencies, so you should leave the file structure intact. To make the Dojo toolkit available, include the dojo.js file as you would any other JavaScript library:
<script language="javascript" src="dojo/dojo.js"></script>

You can also use AOL's Content Distribution Network (CDN) for Dojo. This may make your web page download faster as it's possible the user has visited another site that used AOL's CDN and already has the Dojo files cached.
<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.1.0/dojo/dojo.xd.js"></script>

Our class files use this CDN. If you do not have an internet connection, you need to change the path in the script tag to dojo/dojo.js.

Using Dojo for Ajax


Older Dojo versions including .3 and .4 use the dojo.io.bind object to provide a wrapper around the XMLHttpRequest (XHR) object. The 1.x release of Dojo provides a different function and no longer provides dojo.io.bind. The new version of Dojo provides two functions that expose XHR a little more directly, dojo.xhrGet and dojo.xhrPost.

Both XHR wrapper functions take a single object as an argument. The only difference between them is the HTTP message type used for the XHR object; dojo.xhrGet will cause the XML request to use the HTTP GET type while dojo.xhrPost will use the HTTP POST message type. Since both of these functions are part of Dojo base they are included in the dojo.js file and no dojo.require statement is necessary to ensure that the code is part of the page. The object passed to dojo.xhrGet and dojo.xhrPost has specific properties that control how the actual XHR object is created and how the response from the server is processed. Some of the properties are required but most are optional. The table below describes each of the possible properties. The following table describes the properties in the argument passed to either dojo.xhrGet or dojo.xhrPost.
Request Object Properties Property url Description String. The location of the server resource being requested. Corresponds to the url property of the XHR object. String. A key/value mapping of properties to be constructed into parameters passed with the request. For example, query string parameters in GET requests or form fields in POST requests. Integer. Default: 1000 milliseconds. Number of milliseconds to wait for the server response. When the timeout is exceeded the request should be cancelled and the error callback method should be executed. Object. Reference to the DOM element representing the form. Dojo will iterate through the form elements and create name/value pairs to be passed to the server. The dojo.xhrGet function will pass the data in the URL while dojo.xhrPost will include the data in the body of the HTTP request. Boolean. Indicates whether the result of the request should be cached and whether requesting a result from the cache is acceptable.

content

timeout

form

preventCache

String. Default: text


handleAs

This property determines how Dojo will process the response from the server. When the response is returned, Dojo executes the callback function specified in either the load, error or handle property and passes parameters to the function. The contents of this property determines what object is passed to the callback method.

Request Object Properties Property Description

The following values are possible:


text: the data object passed to the callback method will be a string json: the data object passed to the callback method will be an object built from a JSON string returned from the server xml: the data object passed to the callback method will be a DOM object javascript: the data object passed to the callback method will be the responseText property of XHR. The javascript sent from the server will also be executed by Dojo.

load error handle

The function that will be called to handle the response from the server when the response is not in error. Object. The function that will be called if there is an error in the response. Object. The function that will be called to handle the response from the server for either a successful or unsuccessful response. Specify either handle or both load and error.

Here is the syntax of a simple call to the xhrPost() method:


Syntax
dojo.xhrPost( { url: url, load: callBackFunction, content: { param1: value, param2: value, param3: value } } );

The code sample below shows how we would change part of our EmployeeAdmin.html document to use Dojo.

Code Sample: AjaxFrameworks/Demos/Dojo/EmployeeAdmin.html


<html> <head> <title>Employee Administration</title>

<link rel="stylesheet" type="text/css" href="../Styles/Main.css"> <script type="text/javascript" src="http://o.aolcdn.com/dojo/1.1.0/dojo/dojo.xd.js"></script> <script type="text/javascript"> var OutputDiv; function GetEmployeeList(URL) { OutputDiv = document.getElementById("EmployeeList"); OutputDiv.innerHTML="<h2>Loading...</h2>"; dojo.xhrPost( { url: URL, handleAs: "text", load: Display }); } function Display(DATA) { OutputDiv.style.display="block"; if (DATA.indexOf("Failed") != -1) { OutputDiv.className="Warning"; OutputDiv.innerHTML=DATA; } else { OutputDiv.innerHTML = DATA; } } window.onload = function() { GetEmployeeList("../EmployeeList.jsp"); } </script> </head> ---- Code Omitted ----

Code Explanation

As you can see, we only need to make use of the url, handleAs and method properties of the object that is passed to the xhrPost() method. To pass parameters in with the XMLHttpRequest, we would need to include the content property as well. Another thing to notice is that the callback function (Display()) no longer needs to check the status and the readyState of the xmlhttp object. This is handled by Dojo. The callback function takes a single parameter, which holds the data passed back from the server. The type of this data depends on the handleAs property.

Exercise: Using Dojo for XMLHttpRequests

Duration: 5 to 15 minutes.

In this exercise, you will complete the transition of the EmployeeAdmin.html file to use Dojo instead of our Ajax.js library.
1. Open AjaxFrameworks/Exercises/Dojo/EmployeeAdmin.html for editing. 2. Modify the GetEmployeeForm(), UpdateEmployee(), and EmployeeUpdated() functions to use the Dojo framework. Where is the solution?

Prototype (see footnote)


Prototype is a multi-purpose JavaScript toolkit that, according to its website, "aims to ease development of dynamic web applications." Many other libraries, such as script.aculo.us and Rico are built on top of Prototype and the Ruby on Rails framework has built-in support for Prototype. These tie-ins make it likely that Prototype will be around for a long time. Like Dojo, it is client-side specific so it can be used on any platform with any server-side language. Prototype is now well documented at http://www.prototypejs.org/api. However, before there was good documentation on the Prototype site, Sergio Pereira put together some very good online documentation at http://www.sergiopereira.com/articles/prototype.js.html, which is still available.

Downloading Prototype
The latest version of Prototype is freely available for download at http://www.prototypejs.org/download as a .js file. Rename the file to "prototype.js" and save it in a folder on your web server. We have included a copy of it with your class files (/prototype.js).

Using Prototype for Ajax


To make the Prototype library available, include the prototype.js file as you would any other JavaScript library:
<script language="javascript" src="prototype.js"></script>

XMLHttpRequests are made using the Ajax.Request() class, which, when instantiated, takes two parameters: a URL string and an object, which has the following properties and methods:
Ajax.Request() 2nd Parameter Properties Property Description

Ajax.Request() 2nd Parameter Properties Property method parameters Description String. Method of request. Usually "get" or "post". String. Querystring parameters or form fields in POST requests, using the querystring syntax (e.g, "firstname=Nat&lastname=Dunn") Boolean. Defaults to true. Determines whether the request should be made synchronously. Ajax.Request 2nd Parameter Methods Property Description

asynchronous

Callback method used when onSuccess or onFailure is not defined or not onComplete(xmlhttp) available. The only parameter is a reference to the XMLHTTP object used to dispatch the request. Callback method used when data is successfully returned for this Request. The only parameter is a reference to the XMLHTTP object used to dispatch the request. Callback method used when data cannot be returned for this Request. The only parameter is a reference to the XMLHTTP object used to dispatch the request.

onSuccess(xmlhttp)

onFailure(xmlhttp)

Here is the syntax of a simple call to the Ajax.Request() constructor:


Syntax
new Ajax.Request(URL, { method: "get", //or "post" onComplete: CallBackFunction, parameters: "param1=value&param2=value&param3=value" });

The code sample below shows how we would change part of our EmployeeAdmin.html document to use Prototype.

Code Sample: AjaxFrameworks/Demos/Prototype/EmployeeAdmin.html

<html> <head> <title>Employee Administration</title> <link rel="stylesheet" type="text/css" href="../Styles/Main.css"> <script type="text/javascript" src="../../../prototype.js"></script> <script type="text/javascript" src="../Scripts/Effects.js"></script> <script type="text/javascript"> var OutputDiv; function GetEmployeeList(URL) { OutputDiv = document.getElementById("EmployeeList"); OutputDiv.innerHTML="<h2>Loading...</h2>"; new Ajax.Request(URL, { method: "post", onComplete: Display }); } function Display(REQ) { OutputDiv.style.display="block"; if (REQ.responseText.indexOf("Failed") != -1) { OutputDiv.className="Warning"; OutputDiv.innerHTML=REQ.responseText; } else { OutputDiv.innerHTML = REQ.responseText; } } window.onload = function() { GetEmployeeList("../EmployeeList.jsp"); } </script> </head> ---- Code Omitted ----

Code Explanation

As you can see, we only need to make use of the url property and the second parameter's method property and the onComplete method. To pass parameters in with the XMLHttpRequest, we would need to include the parameters property as well. Like with Dojo, the callback function (Display()) no longer needs to check the status and the readyState of the xmlhttp object as Prototype takes care of this behind the scenes.

Exercise: Using Prototype for XMLHttpRequests

Duration: 5 to 15 minutes.

In this exercise, you will complete the transition of the EmployeeAdmin.html file to use Prototype instead of our Ajax.js library.
1. Open AjaxFrameworks/Exercises/Prototype/EmployeeAdmin.html for editing. 2. Modify the GetEmployeeForm(), UpdateEmployee(), and EmployeeUpdated() functions to use the Prototype framework. Where is the solution?

Throughout the rest of this manual, we will be using Prototype to handle our XMLHttpRequests.

Other Popular Frameworks

Direct Web Remoting (DWR) (see footnote)


DWR is one of the more popular Java-specific frameworks. It makes it possible to call Java methods directly from JavaScript by blackboxing the data transfer to and from the server to make it feel to the developer as if Java objects were natively available to the browser.

AjaxAnywhere (see footnote)


According to its website, "AjaxAnywhere is designed to turn any set of existing JSP or JSF components into AJAX-aware components without complex JavaScript coding." The major benefit of AjaxAnywhere is that it makes it possible to create Ajax applications without writing much JavaScript. The downside is that it does not provide as much flexibility as the more JavaScript-centric solutions.

Simple Ajax (SAJAX) (see footnote)


Like DWR, Sajax allows you to access server-side code directly from JavaScript. It supports ASP, ColdFusion, Perl, PHP, Python, and Ruby, but not Java.

Sarissa (see footnote)


Sarissa is a JavaScript-centric library that isn't specific to any server-side language. It provides a simple function that emulates Mozilla's XMLHttpRequest for Internet Explorer, but that's about it when it comes to client-server communication. It does make using XSLT in the browser very easy.

Other Frameworks

As noted in the beginning of this lesson, there are many more frameworks. For a good list, see http://ajaxpatterns.org/Ajax_Frameworks.

Ajax Frameworks Conclusion


In this lesson of the Ajax tutorial, you have learned about some common Ajax frameworks and how to use a couple of the most popular to handle XMLHttpRequests.
This article is geared towards people with some javascript knowledge, that might have used another ajax/js framework before, but now have a really pressing need to use some of the features found in dojo. So, what is it really? Dojo is quite a lot of things. It has a staggering amount of widgets, to begin with; Dialogs, Panes, Menus, WYSIWYG editors, Buttons, Color pickers, Clocks, Layout Managers and a host of other things- just in the widgets department. Then theres the very handy encryption package, handy for hashing things coming to and from the server-side, the Drag-n-Drop package which works with nearly any element on the page, the essential Collections API with Java-like iterators and whatnot, and of course the powerful proper Ajax functionality with several bells and whistles of its own. Apart from the sheer amount of functionality available in dojo, there are a few architectural differences compared to most other frameworks; Dojo uses namespaces. This means that dojo always includes the package names in an object reference. If I want use the very nice for-each loop function, for instance, I have to refer to is like this; dojo.lang.forEach(listOfThings, myFunc);, instead of just forEach(listOfThings, myFunc);. It seems to be a lot of trouble and waste a lot of space, but in reality its not a big change and it increases readability when debugging or refactoring things later. Another example is that when you want to refer to a DOM element the dojo way, you write dojo.byId(el.id); instead of prototypes inarguably more compact $(el.id); Another big change in philosophy between dojo and prototype is that prototype has a long and glorious history of changing basic javascript objects, such as adding useful new functions to the string object.

This has resulted in collisions or erratic behavior when using other javascript libraries which want to change or assume a certain functionality of the very same function names. By using namespaces, dojo ensures that no collisions occur between itself and any other libraries on the same page. Im going to use the dojo API version 0.4.2 in the examples, since the upcoming 0.9 only has reached milestone 2 as of this writing. Getting the right stuff and copying the right files to your server You might think that using a javascript-based framework should be dead simple. In many cases it is, but due to de facto standards set up by many smaller frameworks (or libraries), this article dojo.js. It is developer. However, when you download and unzip the standard dojo package (dojo 0.4.2-ajax), the dojo.js file is only the starting point, the kernel so to speak, of dojo. All real functionality html files and images that they have to get at, so the short dance version of this everything. Check the test to see how things are done The biggest problem the dojo community faces (IMHO) is the lack of a thorough API documentation and walk-through examples. True, theres a very useful (at least to the be intermediate-level dojo hacker) API tool, and there are several good sites which give found on the test directory which also ships with the standard package. fairly up-to-date walk-throughs and examples in specific areas. But the really good bits can exists and exists only - in files under the src/ directory. Also, most widgets have a lot of template point is; Copy some design choices in dojo requires reading some of the fine print or reading . The most important thing to remember is that dojo is more that just the file not uncommon for people starting to use dojo to assume that the src/ directory

really isnt needed, and probably is shipped only as a kind of open source service to the

If you go to http://download.dojotoolkit.org/release-0.4.2/dojo-0.4.2p1-widget youll see two interesting directories; demo and tests. The reason I refer to the live URL at the dojo download site is that you might want to poke around at other (upcoming) versions. The demo directory contains a fair number of demos, which are neatly organized in the

following

sections; Demo Applications (Mail client, Text editor), Effects (Fades, Wipes, Slides,

et.c.), Drag and Drop, Storage, RPC, Layout Widgets, Form Widgets and General Widgets (Buttons, Menus, Fisheye menus, Tooltips, et.c.). This is a good place to let your jaw drop a bit and get some inspiration. But the really good stuff is found under the tests directory. Here you will find unit tests for almost all widgets, layout containers, graphics, and lots of other things youll find truly useful. The reason the tests are more useful is that they are short, focussed and test_ModalFloatingPane, test_Dialog and test_Menu2_Node for some basic sometimes even (drumrolll, please) commented! My recommendation is to check out tests/widget for examples on how to use dojo widgets. Although dojo is an Ajax framework, much of the truly sterling functionality it offers has little if anything to do with client-sever communication as you will find out. //break// Your first dojo-page Before you do the fancy stuff youre surely shaking with barely controlled desire to do, its a good idea to get a minimal template-page up and running. Of course, you could just grab one of the tests files and change things about, but how fun would that be? Here is a minimal htmlpage to start with, happily snarfed from one of the Dialog tests and shortened a bit; <!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd> <html> <head> <title>My first Dojo page</title> <script type=text/javascript src=dojo.js></script> <script type=text/javascript> dojo.require(dojo.widget.*); </script> <script> var dlg; &n bsp; { function getResults(evt)

var name = dojo.byId(inputname).value; dojo.byId(namediv).innerHTML = <b>+name+</b>; } function init(e) { dlg = dojo.widget.byId(DialogContent); dojo.event.connect(hider, onclick, getResults); } dojo.addOnLoad(init); </script> </head> <body> <a href=javascript:dlg.show()>Show Dialog</a> id=namediv>None</div> <div dojoType=dialog id=DialogContent bgColor=white bgOpacity=0.5 toggle=fade toggleDuration=250 closeNode=hider> <h3>First Dialog</h3> <form onsubmit=return false;> <table> <tr> <td>Name:</td> <td><input type=text id=inputname></td> </tr> <tr> <td>Description:</td> <td><input type=text></td> </tr> <tr> <td>Location:</td> <td><input type=file></td> </tr> <tr> <td colspan=2 align=center> <input type=button id=hider value=OK></td> <br><br>Name:<div

</tr> </table> </form> </div> </body> </html> The first thing that happens here is that we load the file dojo.js, where among other things the dojo.require function is defined. Then we call that require function for the things we really need in our page. We could have just added a lot of script statements to get pretty much the same effect, but whats col with the require loader is that we can use wildcards to load a whole package at a time, for instance dojo.widget.*. This OK when doing happy testing, but in production its a good idea to only load what you need. Note also that the package structure of dojo is the same as the file structure, and actually derives from it. This means that if you create subdirectories for your own dojo-derived widgets or whatever, you can use the loader for them as well. Then comes a script section were we define the variables and setup function to use in the page, which are page-specific. We could have taken these out and put them in a separate file, which we then could load using the standard script tag. As long as its only a dozen lines or so, I actually prefer to have them in the html file, if the logic is tightly coupled (as in this case) to the nearby elements. There are two function, one obvious callback function, which reads the value of an input field, and copies that the value of another element on the page. The other function is a setup function which calls the first function when the form is closed. It does so using dojos own dojo.event.connect function, which is very powerful and requires an article in its own right, but for our purposes here it suffices to say that it hides any browser quirks, to make events simpler to work with. The rest of the page consist of two parts; A link which shows the dialog form, and the dialog form itself. Note the lazy javascript in the href of the anchor tag, which uses the variable defined earlier to show the dialog.

The second part of the page shows the standard dojo way of declaring widgets, by adding a dojotype tag inside the element, which defines the type of widget to be created for the element. Note also the tag closeNode, which defines which node controls calls to the hide() function of the dialog. When the link is clicked on the page, the dialog is shown, and when the OK button is clicked the dialog is hidden and the getResults() function is called.
1. Difference between window.onload and onDocumentReady? The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means theres a huge delay before any code is executed. That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that. 2. What is the difference between == and === ? The == checks for value equality, but === checks for both type and value. 3. What does 1+2+4 evaluate to? What about 5 + 4 + 3? Since 1 is a string, everything is a string, so the result is 124. In the second case, its 93. 4. What is the difference between undefined value and null value? undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object. Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically. 5. How do you change the style/class on any element? document.getElementById(myText).style.fontSize = 20; -ordocument.getElementById(myText).className = anyclass; 6. What are Javascript closures?When would you use them? Two one sentence summaries:

* a closure is the local variables for a function kept alive after the function has returned, or * a closure is a stack-frame which is not deallocated when the function returns. A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created. The following code returns a reference to a function: function sayHello2(name) { var text = Hello + name; // local variable var sayAlert = function() { alert(text); } return sayAlert; } Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it. This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient. 7. What is unobtrusive javascript? How to add behavior to an element using javascript? Unobtrusive Javascript refers to the argument that the purpose of markup is to describe a documents structure, not its programmatic behavior and that combining the two negatively impacts a sites maintainability. Inline event handlers are harder to use and maintain, when one needs to set several events on a single element or when one is using event delegation.
view source

print?

1 <input type="text" name="date" />

Say an input field with the name date had to be validated at runtime:
view source

print?

1 2 3

document.getElementsByName("date")[0]. addEventListener("change", validateDate, false);

4 function validateDate(){ 5 6 // Do something when the content of the 'input' element with the name 'date' is changed. }

Although there are some browser inconsistencies with the above code, so programmers usually go with a javascript library such as JQuery or YUI to attach behavior to an element like above. 8. What is Javascript namespacing? How and where is it used? Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that youve attached all further methods, properties and objects. It promotes modularity and code reuse in the application. 9. What datatypes are supported in Javascript? Number, String, Undefined, null, Boolean 10. What is the difference between innerHTML and append() in JavaScript? InnerHTML is not standard, and its a String. The DOM is not, and although innerHTML is faster and less verbose, its better to use the DOM methods like appendChild(), firstChild.nodeValue, etc to alter innerHTML content.
1. Whats relationship between JavaScript and ECMAScript? - ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. 2. What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined. 3. How do you convert numbers between different bases in JavaScript? - Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16); 4. What does isNaN function do? - Return true if the argument is not a number. 5. What is negative infinity? - Its a number in JavaScript, derived by dividing negative number by zero. 6. What boolean operators does JavaScript support? - &&, || and ! 7. What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124. 8. How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, its concatenation, so 78 is the result. 9. What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach. 10. How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {}; 11. How do you assign object properties? - obj["age"] = 17 or obj.age = 17. 12. Whats a way to append a value to an array? - arr[arr.length] = value; 13. What is this keyword? - It refers to the current object.

The questions below were asked in a preliminary check before the actual interview. The role itself was for a JavaScript Engineer. This particular set of questions is from a job I applied to over a year ago. Ive chosen to share them here because I think readers of this blog would benefit from knowing what kind of things are expected if youre applying to a JavaScript-centric role.

What is the relationship between ECMAScript, Javascript and Jscript? What core types are available in Javascript? What do the following statements return and why?
parseInt("07"); parseInt("09"); parseInt("010"); "1" + 2 + 3; 3 + 2 + "1"; "1" "1" "1" "1" == 1; === 1; == true; === false;

Alert the contents of the bar variable using the foo variable
var foo = "bar"; var bar = "foobar";

Alert the string foobar after a 10 second delay. Implement Array.prototype.filter for IE. Create a Person class with public/private/privileged members and methods. Why does the statement 5 * 1.015 not return 5.075? Replace the string "The quick brown fox jumps over the lazy dog" with the string "The1 quick2 brown3 fox4 jumps5 over6 the7 lazy8 dog9". List several ways that you can communicate asynchronously with the server. How would you embed this URL in a link inside an XHTML document?
http://www.google.com/search?hl=en&q=%22xhtml%22

How would you serve a StyleSheet only to IE users older than IE8? Write a jQuery plugin to display a list of images in a Lightbox