• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this document? Why not share!

Ajax Development

on

  • 18,652 views

AJAX Development and Javascript

AJAX Development and Javascript

Statistics

Views

Total Views
18,652
Views on SlideShare
18,569
Embed Views
83

Actions

Likes
0
Downloads
45
Comments
0

3 Embeds 83

http://www.csesalford.com 75
http://www.slideshare.net 7
url_unknown 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Ajax Development Ajax Development Document Transcript

    • AJAX Development Prepared by : Dave Parkinson Rick Ogden www.webdesigninfo.co.uk (January 2010)
    • AJAX DEVELOPMENT Page 2 AJAX Development This full module runs for 11 weeks ~ 2 hours practical per week. Assessment : 1 assignment MODULE SPECIFICATION Module Title: CRN: University module code: Ajax Development 28982 G400 20063 Level: Credit Value: ECTS Value: Length (in Semester(s) in which to be 10 Semesters): offered: 2 5 1 2 Existing/new Title of Module being replaced (if any): With effect from: module: "Programming on the Internet" Academic year 2008-2009 New Originating School: Module Co-ordinator(s): School of Computing, Science Dave Parkinson and Engineering Programme(s) in which to be offered: P BSc (Hons) Internet Computing (S/IC/F) BSc (Hons) Internet Computing (S/ICT/F) BSc (Hons) Multimedia and Internet Technology (S/MIT/F) Pre-requisites (between levels): Co-requisites (within a level): "Web Page Design" Indicative learning hours: Percentage taught by School(s) other than originating School: 100 (contact hours: 22) Aims of Module: The module aims to provide an introduction to the key technologies used to provide interactive web sites, with strong reference to how to use these technologies whilst still maintaining web standards, particularly accessibility. Intended Learning Outcomes: Upon successful completion of the module, students will be able to: Knowledge and Understanding • use client-side web technologies to create highly interactive web sites; • use the Document Object Model; • assess and discuss the accessibility issues raised by the use of interactive technologies. On completion, students will have the following professional or transferable skills: Professional Skills • Programming in Javascript using Ajax • Representation of simple data in XML and JSON Dave Parkinson
    • AJAX DEVELOPMENT Page 3 Transferable/Key Skills and other attributes • Information Technology - use of computers for web site production. • Communication - presentation and production of written report. • Problem Solving - Apply problem solving skills in practical exercises. Module mark calculation: Method A Assessment components (in chronological order of submission/examination date) Duration Word count (if Component pass Type of assessment Weighting% (if exam) essay/dissertation): required Coursework 100 Learning and teaching strategies: There will be 22 hours of supervised workshops; and 78 hours of independent study and assessed coursework. This makes a total of 100 hours total learning experience. Learning activities will be in the form of weekly 2-hour practical sessions in a computer suite. These will consist of a mixture of lectures, demonstrations of particular programming techniques, and supervised exercises to be performed by the students. Notes will be handed out in the sessions and will be available on Blackboard with example programming files. The coursework will involve the design and creation of an interactive web site, along with a reflective report discussing standards conformance and accessibility issues. Syllabus outline: • What is Ajax? • Javascript and the Document Object Model • Use of the XMLHttp Request • Data Formats (XML, JSON, HTML) • Ajax and Accessibility • Libraries, Frameworks and Toolkits Indicative texts and/or other learning materials/resources: I Keith, J. and Gustafson, A. "Bulletproof Ajax" New Riders 2007; ISBN 0321472667 Keith, J. "DOM Scripting: Web Design with JavaScript and the Document Object Model" Friends of Ed 2005; ISBN 1590595335 AJAX DEVELOPMENT CONTENTS Chapter 1 : What is AJAX........................................................................................................6 1.1 Introduction...................................................................................................................................6 Dave Parkinson
    • AJAX DEVELOPMENT Page 4 Chapter 2 : Basic AJAX Technologies.....................................................................................8 2.1 An Introduction to JavaScript......................................................................................................8 2.1.1 Statements....................................................................................................................................................8 2.1.2 Comments....................................................................................................................................................8 2.1.3 Variables......................................................................................................................................................9 2.1.4 Data Types...................................................................................................................................................9 2.1.5 Operators....................................................................................................................................................11 2.1.6 Decision Making and Flow Control..........................................................................................................12 2.1.7 Functions ...................................................................................................................................................16 2.1.8 Scope.........................................................................................................................................................17 2.1.9 JavaScript Event Handling........................................................................................................................17 2.2 Writing JavaScript Web Pages...................................................................................................18 2.2.1 Exercise 1 - My First JavaScript Web Page.............................................................................................19 2.2.2 Exercise 2 – Interaction with a JavaScript Web Page..............................................................................21 Chapter 3 : The Document Object Model..............................................................................23 3.1 Introduction.................................................................................................................................23 3.2 Basic DOM Methods – Exercise3...............................................................................................25 3.2.1 getElementById.........................................................................................................................................26 3.2.2 getElementsByTagName...........................................................................................................................26 3.2.3 getAttribute................................................................................................................................................27 3.2.4 setAttribute................................................................................................................................................27 3.3 Creating Markup using DOM Methods....................................................................................27 3.3.1 createElement............................................................................................................................................28 3.3.2 appendChild...............................................................................................................................................28 3.3.3 createTextNode..........................................................................................................................................28 Chapter 4 : Unobtrusive JavaScript.......................................................................................30 4.1 Introduction.................................................................................................................................30 4.2 Using eventListener.....................................................................................................................30 4.2.1 Exercise 4 – Miles to Kilometre Convertor..............................................................................................31 4.2.2 Exercise 5 – Changing the Styling of a Document...................................................................................35 Chapter 5 : MooTools JavaScript Framework......................................................................39 5.1 Introduction.................................................................................................................................39 5.2 MooTools......................................................................................................................................39 5.2.1 Elements....................................................................................................................................................39 5.2.2 Creating and Editing an Element..............................................................................................................40 5.2.3 Events.........................................................................................................................................................41 5.2.4 Exercise 6 – Miles to Kilometre Converter using MooTools..................................................................42 5.2.5 Exercise 7 – Calculator using MooTools..................................................................................................44 5.2.6 MooTools Effects......................................................................................................................................44 5.2.7 Example 8 - Styling Elements using MooTools.......................................................................................46 5.2.8 MooTools Class.........................................................................................................................................47 Chapter 6 : XMLHttpRequest.................................................................................................49 6.1 Introduction.................................................................................................................................49 6.2 Using the XMLHttpRequest object............................................................................................49 6.3 Data Formats...............................................................................................................................49 6.3.1 XML...........................................................................................................................................................50 6.3.2 JSON..........................................................................................................................................................50 6.3.3 HTML........................................................................................................................................................51 6.4 MooTools Request.......................................................................................................................51 6.4.1 Example 10 – Reading a JSON file using MooTools...............................................................................53 Dave Parkinson
    • AJAX DEVELOPMENT Page 5 Chapter 7 : Accessing a MySQL Database............................................................................56 7.1 Introduction.................................................................................................................................56 7.2 Exercise 11 - Accessing data from a MySQL Database............................................................58 7.2.1 Setting up a MySQL Database..................................................................................................................59 7.2.2 Reading from a MySQL Database............................................................................................................61 7.2.3 Inserting into a MySQL Database.............................................................................................................65 7.2.4 Editing an entry in a MySQL Database....................................................................................................67 7.2.5 Deleting an entry in a MySQL Database..................................................................................................69 7.2.6 Extending Exercise 11 to include multiple threads .................................................................................71 .................................................................................................................................................71 Dave Parkinson
    • AJAX DEVELOPMENT Page 6 Chapter 1 : What is AJAX 1.1 Introduction Ajax, or AJAX (Asynchronous JavaScript and XML), is a group of interrelated web development techniques used to create interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behaviour of the existing page. The term was first introduced in an article by Jesse James Garrett of Adaptive Path, a web-design firm based out of San Francisco. He conceived of the term when he realized the need for an easy, sellable way to pitch a certain style of design and building to clients. The primary purpose of AJAX is to help make web applications function more like desktop applications, and save bandwidth by nor refreshing the whole page. The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax, Jesse James Garrett explained that it refers specifically to these technologies: * XHTML and CSS for presentation * the Document Object Model for dynamic display of and interaction with data * XML and XSLT for the interchange, manipulation and display of data, respectively * the XMLHttpRequest object for asynchronous communication * JavaScript to bring these technologies together On traditional web sites, the browser requests an entire page from the server. Then, the user clicks on a link or submits a form, at which point the browser sends a new request to the server. The server then sends another page. Dave Parkinson
    • AJAX DEVELOPMENT Page 7 The Ajax methodology moves away from this page based model. When the user interacts with the a page, the server sends back a discrete piece of information. Rather than serving up an entire page, the currently loaded page is updated. For the user this represents a more fluid experience. While traditional Web sites present users with a start stop response, Ajax applications can offer faster and more responsive feedback, continuously. A simplified definition of Ajax is: “A way of communicating with a web server without refreshing the whole page.” Dave Parkinson
    • AJAX DEVELOPMENT Page 8 Chapter 2 : Basic AJAX Technologies 2.1 An Introduction to JavaScript The most important technology for a Web Designer is HTML. Without a markup language you cannot give your content any structure. Once the markup structure is in place, it can be enhanced with other technologies such as CSS and JavaScript Whereas HTML is a markup language, JavaScript is a programming language. Instead of specifying structure, it performs logical operations and calculations. The key feature of JavaScript is that it can run in a Web browser. On the web, the browser acts as a interpreter, capable of executing instructions that are written in the JavaScript language. Like CSS, JavaScript can be embedded in a web page, often within the head element. The most efficient way to use JavaScript, as with CSS, is to keep it in external files. These files can then be referenced by a web page using <script> tags in the documents head e.g. <script type=”text/javascript” src=”/directory/file.js”></script> Note all tags must use proper closing tags, not short cuts. JavaScript is case sensitive. 2.1.1 Statements A single JavaScript instruction is called a statement. A sequence of statements is a script. A statement should always end in a semicolon (although if JavaScript sees a new line it will insert a semicolon for you). statement one; statement two; 2.1.2 Comments There are a number of ways to specify comments in JavaScript. To create a single line comment in JavaScript, you place two slashes "//" in front of the code or text you wish to have the JavaScript interpreter ignore. When you place these two slashes, all text to the right of them will be ignored, until the next line. // This is a single line JavaScript comment For this large comments you can use JavaScript's multi-line comment that begins with /* and ends with */. Dave Parkinson
    • AJAX DEVELOPMENT Page 9 /*document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!");*/ Although comments are very useful in documenting your code it is important to remember that every comment adds to the page weight and download time, so don’t go overboard with comments. 2.1.3 Variables A variable's purpose is to store information so that it can be used later. A variable is a symbolic name that represents some data that you set. When using a variable for the first time it is not necessary to use "var" before the variable name, but it is a good programming practice to make it crystal clear when a variable is being used for the first time in the program e.g. var variablename; Variable names can be made up of letters, numbers (although they cannot begin with numbers), underscores and some other characters. Spaces cannot be used in variable names. Remember variable names are case sensitive. JavaScript has a number of reserved words that cannot be used as variable names. Most of these are keywords that are used by the language itself. Reserved Words abstract else instanceof switch boolean enum int synchronized break export interface this byte extends long throw case false native throws catch final new transient char finally null true class float package try const for private typeof continue function protected var debugger goto public void default if return volatile delete implements short while do import static with double in super 2.1.4 Data Types Dave Parkinson
    • AJAX DEVELOPMENT Page 10 When a variable is first declared its value is null, it contains no data. Providing a value for a variable is called assignment. You can assign a value to a variable using the equals sign. The value of a variable can be an string, a number, a Boolean value, or an array. Thease are called data types. Some programming languages insist that you declare a variable type before using it. In these languages you cannot change the type latter on. This is called strong typing. JavaScript is a weakly typed language. You don’t have to specify what type of value your variable will contain. You can also change the data type of a variable at any stage. Strings A string is a collection of characters. There are no forbidden characters in strings. Strings can contain letters, numbers, spaces etc. A string must be enclose in quotation marks. You can use either double or single quotation marks but you must be consistent within a string. var name; name = “Dave Parkinson”; You can declare a variable and assign it in one statement. var name = “Dave Parkinson”; Multiple declarations and assignment can be done on one line using commas to separate variables. var first_name = “Dave”, last_name = “Parkinson”; Sometimes you may need to use a quotation mark within a string. This is known as escaping and you use a backslash to escape characters. var remark = ‘That’s my name’; Numbers To use numbers you simply assign the number to the variable e.g. var year = 2009; var score = -50; var average = 5.62; Boolean Values There are only two possible values for a variable that contains a Boolean, true or false. var happy = true; var rich = false; Arrays An array can hold multiple values of one variable. To set up an array in JavaScript you have to create an array object. This involves using the word new. seasons = new Array(3) Dave Parkinson
    • AJAX DEVELOPMENT Page 11 or you can use brackets as shorthand. var seasons = [ ] The above code would set up an array that could hold four different values in it (arrays start at zero). To put something into each "slot" in the array, you'd just do this: seasons[0] = "Winter" seasons[1] = "Spring" seasons[2] = "Summer" seasons[3] = "Autumn" Our array is called seasons. In between round brackets, we had an upper limit for the array 3. (The number in round brackets is called the Index). When we're assigning values to each position in the array, we just type the name of the array, and then one of the numbers in square brackets. After typing the assignment operator (=), we type the value we want to go into that "slot" of the array. Another way to set up an array is to have all the values inside the round brackets of the word Array. Like this: seasons = new Array("Winter", "Spring", "Summer", "Autumn") We still have an array with four values in it, but we've fixed the values inside of the round brackets. To get at the value inside an array, just use its index number. There is another kind of array called an associative array or hash. In an associative array, strings are used for the indices instead of numbers. var details = [ ]; details[“name”] = “Dave Parkinson”; details[“age”] = 21; details[“phone”] = 01612954476; In this case details[“age”] will return 21. 2.1.5 Operators The manipulation of data involves expressions that are made up of operands and operators. Operators are special symbols that take the value of operands and produce a new value. Each category of operator manipulates data in a specific way. Arithmetic Operators Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y=5, the table below explains the arithmetic operators: Operator Description Example Result + Addition x=y+2 x=7 Dave Parkinson
    • AJAX DEVELOPMENT Page 12 - Subtraction x=y-2 x=3 * Multiplication x=y*2 x=10 / Division x=y/2 x=2.5 % Modulus (division remainder) x=y%2 x=1 ++ Increment x=++y x=6 -- Decrement x=--y x=4 The + operator serves a dual role. As well as adding numbers, it can join strings together. var txt1 = "What a very"; var txt2 = "nice day"; var txt3 = txt1 + txt2; After the execution of the statements above, the variable txt3 contains "What a verynice day". To add a space between the two strings, insert a space into one of the strings. Assignment Operators Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators: Operator Example Same As Result = x=y x=5 += x+=y x=x+y x=15 -= x-=y x=x-y x=5 *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0 Comparison Operators Not all operations are mathematical. Sometimes you will want to compare one value with another. Comparison operators allow you to do this. Like C++, C#, Visual Basic and Java, JavaScript supports all the common decision making and flow control statements (if statements, do loops, while loops, for loops etc). You test variable values and perform appropriate tasks using conditional operators == for equals, >, <, >=,<=, && for And, || for OR. 2.1.6 Decision Making and Flow Control Most programs involve the use of conditional statements to control the flow of the program. Decision-making constructs allow your application to examine conditions and choose courses of action. Javascript allows several decision-making constructs. The Single-Alternative if Statement Dave Parkinson
    • AJAX DEVELOPMENT Page 13 Most programs involve taking different actions dependant on the result of some operation or the value of some parameter. In Javascript this type of action is accounted for using the if statement. The general syntax of the single-alternative if statement is :- if ( condition) { sequence of statements; } This is interpreted as if the condition-expression is true then carry out the action(s) denoted in the following statement(s). If the condition-expression is not true the statement(s) are bypassed. Example : if (height == 10) { length = 15; depth = 20; } The Dual-Alternative if-else Statement The general syntax of the dual-alternative if-else statement is :- if ( condition) { sequence of statements A; } else { sequence of statements B; } This is interpreted as if the condition-expression is true then carry out the action(s) denoted in the sequence of statements (A). If the condition is not true then carry out the sequence of statements (B). if(message == "hello" && happy == “true”) { reply = "hello to you too"; } else { reply = "be that way"; } The Multiple-Alternative if-else Statement JavaScript enables you to nest if-else statements to create a multiple-alternative form. The general syntax of the multiple-alternative if-else statement is :- if ( condition 1) statement 1; or {sequence of statements 1} else if (condition 2) statement 2; or {sequence of statements 2} Dave Parkinson
    • AJAX DEVELOPMENT Page 14 ........ else if (condition n) statement n; or {sequence of statements n} else statement; or {sequence of statements} The multiple-alternative if-else statement performs a series of cascaded tests until one of the following occurs :- 1. One of the conditions in the if clause or in the else if clause is true. In this case the accompanying statements are executed. 2. None of the tested conditions are true. The program then executes the statements in the catch-all else clause (note this else clause is optional). For example:- var x=0, y=0; if(x>10) { y=1; } else if(x>20) { y=2; } else if(x>30) { y=3; } else { y=4; } Switch Statement The switch statement offers a special form of multiple-alternative decision making. It enables you to examine the various values of an integer compatible expression and choose the appropriate course of action. The general syntax of the switch statement is :- switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } Dave Parkinson
    • AJAX DEVELOPMENT Page 15 The switch statement works as follows. First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. While Loop The while loop in Javascript is another conditional loop that iterates as long as a condition is true. A while loop may not iterate if the condition tested is initially false. statements True condition ? False The general syntax for the while loop is :- while (condition) { statements; } For example while(i < 10) { sum = sum + prime_numbers[i]; i = i + 1; } Do…While Loop The do-while loop is a conditional loop that tests the iteration condition at the end of the loop. A conditional loop will iterate as long as a particular condition is true. statements True condition ? False The general syntax for the do-while loop is :- Dave Parkinson
    • AJAX DEVELOPMENT Page 16 do { statements; } while (condition); var i=0; do { document.write("The number is " + i); document.write("<br />"); i=i+1; } while (i<0); For Loop The for loop is a versatile loop because it offers both fixed and conditional iterations. The general syntax for the for loop statement is :- for (counter initialisation; loop test condition; loop modifier) { sequence of statements; } statement after loop; The for loop statement has three components, each of which is optional. The first component initialises the loop control variables. The second part of the loop is the condition that determines whether or not the loop makes another iteration. The last part of the for loop is the clause that increments and/or decrements the loop control variables. for (i=0;i<=10;i++) { document.write("The number is " + i); document.write("<br />"); } 2.1.7 Functions To avoid excessive amounts of code it is often desirable to group regularly used statements into member functions (often called methods). Functions take input variables (often called arguments or parameters), and can output a result variable called the return value. Functions are firstly declared. For example… function multiply(a,b) Dave Parkinson
    • AJAX DEVELOPMENT Page 17 { var result = a * b; return result; } A function does not have to return a value but if it does you can assign the result of a function to a variable var days_old = multiply (35, 365); 2.1.8 Scope If you declare a variable outside of a function, it is called a global variable. That means it can be used anywhere, even inside functions. A local variable is declared within a function. It cannot be accessed outside the function in which it is declared. When we talk about where variables can be used, we are discussing variable scope. Variables declared within functions have local scope. Variables declared outside functions have global scope. 2.1.9 JavaScript Event Handling By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger JavaScript functions. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Examples of events: • A mouse click • A web page or an image loading • Mousing over a hot spot on the web page • Selecting an input box in an HTML form • Submitting an HTML form • A keystroke Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! New to HTML 4.0 was the ability to let HTML events trigger actions in the browser, like starting a JavaScript when a user clicks on an HTML element. Below is a list of the attributes that can be inserted into HTML tags to define event actions. Dave Parkinson
    • AJAX DEVELOPMENT Page 18 Attribute The event occurs when... onabort Loading of an image is interrupted onblur An element loses focus onchange The user changes the content of a field onclick Mouse clicks an object ondblclick Mouse double-clicks an object onerror An error occurs when loading a document or an image onfocus An element gets focus onkeydown A keyboard key is pressed onkeypress A keyboard key is pressed or held down onkeyup A keyboard key is released onload A page or an image is finished loading onmousedown A mouse button is pressed onmousemove The mouse is moved onmouseout The mouse is moved off an element onmouseover The mouse is moved over an element onmouseup A mouse button is released onreset The reset button is clicked onresize A window or frame is resized onselect Text is selected onsubmit The submit button is clicked onunload The user exits the page Note that when using JavaScript event listeners remove the on i.e. click, blur, etc. 2.2 Writing JavaScript Web Pages Dave Parkinson
    • AJAX DEVELOPMENT Page 19 You can use any editor including Notepad to generate web pages containing JavaScript. In this module we will be using Aptana Studio to develop our web pages. Aptana Studio is an IDE (Integrated Development Environment) for Web Developers offering integrated language support for HTML, DOM, JavaScript and CSS, embedded development platforms and databases for PHP, Jaxer, Ruby on Rails, and Python. Plus support for emerging platforms that use Ajax like Adobe AIR and Apple iPhone. Aptana Studio is free, open source software based on the Eclipse tools platform. Although Aptana Studio can be used as a plug in to the Eclipse development platform we will be using it in standalone mode. Aptana Studio can be downloaded for free from www.aptana.com 2.2.1 Exercise 1 - My First JavaScript Web Page Open Aptana Studio and set you workspace to point to a folder called Ajax Development on your f: drive or on a pen drive. Aptana Studio will open as shown below: Select File – New – Project Select a Default Web Project (under Aptana Projects) as shown below: Dave Parkinson
    • AJAX DEVELOPMENT Page 20 Name the project exercise1 and do not select any JavaScript libraries or include the Jaxer server in your project. Ignore the HTML Preview settings and press Finish. You will be presented with a basic HTML page (index.html). Try previewing the page in Firefox and Explorer using the tabs in the window. Edit the code to include some basic JavaScript as shown below: <body> <h1>New Web Project Page</h1> <script type="text/javascript"> document.write("Hello World!"); </script> Dave Parkinson
    • AJAX DEVELOPMENT Page 21 </body> Test your program. It should display the following: 2.2.2 Exercise 2 – Interaction with a JavaScript Web Page JavaScript provides many events that can trigger actions within your JavaScript program. One of these is the onclick event. If we attach this event to a button, when the button is clicked we can run a function. Within JavaScript we can create three kinds of popup boxes: Alert box, Confirm box, and Prompt box. Alert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax: alert("sometext"); Confirm Box A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax: confirm("sometext"); Prompt Box A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax: prompt("sometext","defaultvalue"); We can now write a program to display a button which when clicked will display an alert box. Consider the following web page: <html> <head> <script type="text/javascript"> function disp_alert() { Dave Parkinson
    • AJAX DEVELOPMENT Page 22 alert("I am an alert box!!"); } </script> </head> <body> <input type="button" onclick="disp_alert()" value="Display alert box" /> </body> </html> Within the body section of the web page note that we have added button and used the associated onclick event to run a function called disp_alert. This function opens an alert box displaying the specified text. Open a new project called exercise2. Input the above code and test your program. Try modifying your program to change from an alert box to a prompt box. The prompt box should ask you to enter your name as shown below: On pressing enter it should then welcome you with a message “Hello Dave, how are you today”. Try using an if statement to test that the prompt box has data entered into it. If not the prompt box button should remain on the web page. It is good practice to contain all your JavaScript code within a separate file. Add a new JavaScript file to your program (called exercise2.js) and move your script code to this file. Add the JavaScript file to your HTML page by adding the following line to the Head section of your HTML page: <script type="text/javascript" src="exercise2.js"></script> Test your completed application by selecting Run – Run As – 1 JavaScript Web Application. Dave Parkinson
    • AJAX DEVELOPMENT Page 23 Chapter 3 : The Document Object Model 3.1 Introduction The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. With the Document Object Model, programmers can build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model. The most important convention used by the Document Object Model is the representation of a document as a family tree. A family tree represents a real family describing the relationships between family members, like parent, child and sibling. The family tree model works just as well representing a document written in HTML. To understand the meaning of these terms let’s look at a very basic web page: The markup representing this web page is shown below: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" Dave Parkinson
    • AJAX DEVELOPMENT Page 24 "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Shopping List</title> </head> <body> <h1>What to buy</h1> <p title="a gentle reminder">Don't forget to buy the items</ p> <ul id="purchases"> <li>A tin of beans</li> <li>Cheese</li> <li>Milk</li> </ul> </body> </html> This can be represented by the model below: Let’s look through this web page and see how it can be represented by the family tree model. After the Doctype declaration the document begins by opening an <html> tag. All the other elements of the web page are contained within this element meaning it is a parent. Because all the other elements are inside this tag, then the <html> tag has no parent or no siblings. If this were a tree then the <html> tag would be the root. If we move one level deeper, we find two branches: <head> and <body>. They exist side by side, which makes them siblings. They share the same parent <html>, but they also both contain children so they are parents themselves. The <head> element has two children: <meta> and <title> (siblings of one another. The children of the <body> element are <h1>, <p>, and <ul> (all siblings of one another). If we drill down even deeper we find that <ul> is also a parent. It has three children, all of them <li> elements. Dave Parkinson
    • AJAX DEVELOPMENT Page 25 By using this simple convention of family relationships, we can access lots of information about the relationships between elements. Ask yourself the following questions: 1. What is the relationship between <h1> and <p> 2. What is the relationship between <body> and <ul> If you can think of the elements of a document in terms of a family tree then you are using the same terms as the DOM. However, instead of using the term ‘family tree’ it is more accurate to call a document a ‘node tree’. Nodes A document is a collection of nodes, with nodes as the branches, and leaves on the document tree Element Nodes Elements are the basic building blocks of a document on the web e.g. <html>, <head>, <body>, <p>, <ul> etc. It is the arrangement of these elements in a document that gives the document its structure. The tag provides the name of an element. Paragraph elements have the name p, unordered lists have the name ul, and list items have the name li. Elements can contain other elements. For example, all the list item elements in our document are contained within an unordered list element. Text Nodes Elements are just one type of node. If a document consisted purely of empty elements it would have structure but no content. In our example, the <p> element contains the text “Don't forget to buy the items”. This is a text node. Attribute Nodes Attributes are used to give more specific information about an element. The title attribute for example, can be used on just about any element to specify exactly what the element contains. <p title="a gentle reminder">Don't forget to buy the items</p> In the DOM, title=”a gentle reminder” is an attribute node. Because attributes are always placed within an opening tag, attribute nodes are always contained within element nodes. 3.2 Basic DOM Methods – Exercise3 Dave Parkinson
    • AJAX DEVELOPMENT Page 26 This DOM interface provides methods for accessing, changing and creating other nodes in the document tree. In order to test these methods you should first create a new project in Aptana Studio. Name the project exercise3 and add the ‘Shopping’ web page shown earlier. 3.2.1 getElementById This DOM method allows you to get straight to the element node with the specified id. This method is a function associated with the document object and takes one argument, the id of the element you want to get to (contained in either single or double quotes. For example: document.getElementById(“purchases”) This is referencing the unique element that has been assigned the HTML id attribute “purchases” in the document object. The element corresponds to an object. In fact every single element in a document is an object. In order to test this method add the following code on the next line after the closing ul tag </ul> in your ‘Shopping’ web site. <script type=”text/javascript”> alert(typeof document.getElementById(“purchases”)); </script> The typeof function reports what the element is, in this case an object. This is shown in the alert pop-up box. Obviously you should not give a unique id to every single element in a document. That would be overkill. Fortunately, the DOM provides another method for getting at elements that don’t have unique identifiers. 3.2.2 getElementsByTagName This Dom method gives you access to an array populated with every occurrence of a specified tag in the order that they appear in the document. It takes one argument, the name of the tag. For example: document.getElementsByTagName(“li”) This returns an array populated with all the list items in the document object. You can use the array length property to find the total number of elements. Replace the alert statement between the <script> tags with the following code: var items = document.getElementsByTagName("li"); for (var i=0; i < items.length; i++) { alert(typeof items[i]); } Dave Parkinson
    • AJAX DEVELOPMENT Page 27 This code loads each of the <li> elements into an array called items. The for loop goes through the array one at a time and outputs an alert box giving the type of object for each element. You should see three pop-up boxes. 3.2.3 getAttribute So far we have looked at methods of getting to element nodes. Once you have got to the element, you can find the value of any of its attributes using the getAttribute method. Unlike other methods to date you cannot use the getAttribute method on the document object. It can only be used on an element node object. It must therefore be used in conjunction with one of the other methods. For example: var parray = document.getElementsByTagName(“p”); for (var i=0; i < parray.length; i++) { alert(parray[i].getAttribute(“title”)); } Replace the code between the <script> tags with the above code. In our Shopping site there is only one <p> element and that has a title attribute. If there were more <p> elements without title attributes they would return the value null (in JavaScript, null means no value). 3.2.4 setAttribute All of the methods to date have dealt with retrieving information. The setAttribute method allows you to change the value of an attribute node. For example: var shopping = document.getElementById("purchases"); alert(shopping.getAttribute("title")); shopping.setAttribute("title","a list of goods"); alert(shopping.getAttribute("title")); Replace the code between the <script> tags with the above code. Loading the page should now give two alert boxes. The first one, which is executed before setAttribute should display null. The second one, executed after the title attribute has been set says “a list of goods”. 3.3 Creating Markup using DOM Methods The DOM methods we have examined so far have all been applied to previously existing markup. We are now going to look at DOM methods that can alter the structure of a web page by creating new elements and modifying existing ones. Dave Parkinson
    • AJAX DEVELOPMENT Page 28 3.3.1 createElement The index.html file should contain an empty <div> with the id value of “testdiv”. <div id="testdiv"> </div> Let’s consider the case where we wish to insert a paragraph into “testdiv”. In the language of the DOM this means adding a p element node as a child node of the div element node (which already has one child node, an id attribute node with the value “testdiv”). To achieve this we need a two step process: 1. Create the new element 2. Insert the element into the DOM tree The first step can be achieved using a DOM method called createElement. For example to create a paragraph element: document.createElement(“p”); Usually you need to refer to this element so it a good idea to assign the newly created element to a variable i.e. var para = document.createElement(“p”); 3.3.2 appendChild The element we created above is floating in JavaScript limbo. The element exists but is not part of the DOM tree. The simplest ways of inserting a new node is to make it a child of an existing node in the document. If we wish to add a new paragraph to the element node identified by “testdiv” we can do this with appendChild. For example: var para = document.createElement(“p”); var testdiv = document.getElementById(“testdiv”); testdiv.appendChild(para); Note that we have to use getElementByID to reference the “testdiv” element node. 3.3.3 createTextNode We have now created an element node and inserted it into the node tree of the document. However, the node we have created is an empty paragraph element. If you wish to put some text into the paragraph you can use createTextNode. We can create a new text node and assign it to a variable as shown below: var txt = document.createTextNode(“Hello World”); Dave Parkinson
    • AJAX DEVELOPMENT Page 29 We can then use appendChild to insert the text node into the paragraph element we created earlier. para.appendChild(txt); Try modifying the onload function in your example4.js file. window.onload = function() { var para = document.createElement("p"); var testdiv = document.getElementById("testdiv"); testdiv.appendChild(para); var txt = document.createTextNode("Hello World"); para.appendChild(txt); } When you run the web page you should see the text “Hello World” in the browser window. Dave Parkinson
    • AJAX DEVELOPMENT Page 30 Chapter 4 : Unobtrusive JavaScript 4.1 Introduction JavaScript has long had a reputation as a clumsy, hackish language unsuitable for serious application development. This has been largely due to inconsistent implementations of the language itself and the Document Object Model in various browsers, and the widespread use of buggy cut-and-paste code. Runtime errors were so common (and so difficult to debug) that few programmers even tried to fix them, as long as the script behaved more or less the way it was supposed to; scripts often failed completely in some browsers. The recent emergence of standardized browsers, JavaScript frameworks and high-quality debugging tools have made organized, scalable JavaScript code possible, and the emergence of AJAX has made it essential. Whereas JavaScript was once reserved for relatively simple and non-critical tasks such as form validation and decorative novelties, it is now being used to write large, complex codebases that are often part of a site's core functionality. Runtime errors and unpredictable behaviour are no longer minor annoyances; they are fatal flaws. In modern programming practices, it is always beneficial to keep the code and the display separate. This allows different groups of people to work on individual parts of a web application without risk of interfering, and also allows for scalability of a program. This technique is called “unobtrusive JavaScript”. Unobtrusive JavaScript can be seen as part of the larger Web standards movement; much as the demand for cross-browser compatibility has driven the increasing emphasis on standardized markup and style, the increasing demand for rich Internet applications is driving the movement toward the more robust methods of unobtrusive JavaScript. The term was invented in the 2002 by Stuart Langridge. 4.2 Using eventListener Traditionally, JavaScript often was placed inline together with an HTML document's markup. For example, the following is a typical implementation of JavaScript form validation when written inline: <input type="text" name="date" onchange="validateDate(this);" /> However, the purpose of markup is to describe a document's structure, not its programmatic behaviour. Combining the two negatively impacts a site's maintainability for the same reason that combining content and presentation does: if a site contains hundreds of such date fields, adding the appropriate onchange attribute for each one (and modifying them later, if necessary) can be a labour-intensive process. Furthermore, inline syntax prevents the registration of more than one event handler for the element's onchange event, which can be a problem as the application grows. The whole idea of using attributes in the xhtml such as “onclick”, “onchange” etc... directly contradicts the idea of unobtrusive JavaScript, and thus is now no longer Dave Parkinson
    • AJAX DEVELOPMENT Page 31 recommended in modern day JavaScript programming. The current W3C recommendation is to use the addEventListener( ) method, which will assign functions to elements of the DOM, and allow the functions to be fired when the event occurs. AddEventListener takes 3 parameters: event, function, and whether it is caught or bubbled through (a boolean value). The event uses the W3C attribute names, without the “on” prefix. So for example “onclick” becomes “click”, “onchange” becomes “change” etc. When the function is assigned to an element, it is also bound to it, meaning that the “this” keyword is used to refer to the element. Finally, the boolean value is set to “true” if it is to be caught, or “false” if it is to be bubbled through. If in doubt, use “false”. Here is an example: el.addEventListener('click',myFunction, false); function myFunction(){ this.style.backgroundColor = '#999'; } The term el refers to an HTML element For example, this can also be used with an onload event on the window, which will execute code when the whole window has finished loading: window.addEventListener('load',function(){ el.addEventListener('click', myFunction, false); }, false); You can add multiple event listeners within this method. By setting the final Boolean value to false you ensure the event listeners are executed in the order in which they appear. The downside of this method is although it is universally accepted as the correct way of doing it, Microsoft has other ideas, and has proposed it own solution to the problem. Hence there are compatibility problems with the above solution and IE. Using frameworks will get round this problem. Frameworks check to see which browser you are working in and execute the correct code for that browser. 4.2.1 Exercise 4 – Miles to Kilometre Convertor Start a new project in Aptana Studio called exercise4. With this exercise we will create a JavaScript program that converts from Miles to Kilometres. We will use an event listener and all the JavaScript code will be held in an external file. Add a new HTML page called index.html. Add the following HTML code within the body section. <div> <form method="post" action="#" id="converter"> <div> Dave Parkinson
    • AJAX DEVELOPMENT Page 32 <label>Convert</label> <input name="val" type="text" /> <label>miles into kilometers</label> <br/> <input type="submit" value="convert" /> <br/> <span id="result"></span> </div> </form> </div> When viewed in the internal browser this will display: Now add a JavaScript file to your project. Name the file convert.js Add the following code to your JavaScript file: /** * Attaches the function converter() to the element with the id * 'converter', and is fired when it is submitted. */ window.addEventListener('load',function(){ document.getElementById('converter').addEventListener('submit', converter, false); }, false); /** * Retrieves the data from the form, using the 'this' keyword, as the function * is bound to the form. It in turn calls the function performConvert(), * and displays the result. * * @param {Object} e The event that has been fired */ function converter(e){ alert('The result is ' + performConvert(this.val.value)); } /** * Performs the calculation to convert the units, and then returns the * result. * * @param {Number} value The value to be converted * @return the conversion result * @type Number */ function performConvert(value){ var result result = value * 1.609; return result; } Dave Parkinson
    • AJAX DEVELOPMENT Page 33 Don’t forget to include your JavaScript file into your HTML code by adding the following in the HTML head section: <script type="text/javascript" src="convert.js"></script> When you run the program it will display the result of your calculation in an alert box. Although the program appears to function as we expect, if you hit he OK button following the calculation you will get a message telling you that you are about to send information to a third party. When you press OK you will return to your page but the text box will now be empty. What is happening? The problem is that we are using a Submit button to start our calculation. The normal use of a submit button is to send information to a web server. When the information is sent the page is then refreshed and we lose the data in the textbox. We can prevent this behaviour by adding the following code: e.preventDefault( ); This statement stops the default event from firing (i.e. in this case it will prevent the submit button from submitting the form). Another improvement we should make to our code is to add some error checking to our code to ensure only a number is entered in the textbox. Change your converter function as shown below: function converter(e){ e.preventDefault(); if (isNaN(this.val.value)) { alert('not a number'); } else { alert('The result is ' + performConvert(this.val.value)); } } Dave Parkinson
    • AJAX DEVELOPMENT Page 34 A further improvement to the program would be to program would be to add a select box to the HTML to enable you to select whether you wish to convert from Miles to Kilometres or Kilometres to Miles as shown below: The HTML to add the select box is shown below: <div> <form method="post" action="#" id="converter"> <div> <label>Convert</label> <input name="val" type="text" /> <label>into</label> <select name="unit"> <option>km</option> <option>miles</option> </select> <br/> <input type="submit" value="convert" /> <br/> <span id="result"></span> </div> </form> </div> Try to modify your JavaScipt code to check the value of this select box and perform the appropriate calculation. HINT: You can retrieve the value of the selection box using a similar method to how we get the value of the textbox i.e. this.unit.value If you pass this value into the performconvert function in the same way as we pass the textbox value, you can then use a switch statement (or an if statement) to test the value of the select box and then perform the calculation. You final program should output the following: Dave Parkinson
    • AJAX DEVELOPMENT Page 35 As a final improvement to our program we can change the way the result of the calculation is displayed. Instead of outputting the result in an alert box we can output it directly to the screen as was described in the previous chapter (try using the DOM method to achieve this). You final program should look like this: 4.2.2 Exercise 5 – Changing the Styling of a Document As well as changing the content of a document we can use DOM methods to change the style of elements within the web page. JavaScript supports a style attribute that allows you to override any CSS styles or HTML styles in your document. For example, if we wish to change the background colour of an element on the web page given an id = “test” we can use the following: document.getElementById('test').style.backgroundColor = “#F00"; Note on Colour - There are five different ways to specify colours in CSS; four use numeric RGB values and one uses named colours. The two most efficient ways are hexadecimal and named colours. Hexadecimal colours come in two flavours: RGB triplets and shorthand. So instead of the colour orange being described by 24 bits (#ff6600), you can use the shorthand (#f60). Nearly all browsers support shorthand hex colours. RGB triplets can be abbreviated if each of the Red, Green, and Blue hex pairs are the same. So when you use colours where there are three pairs, you can abbreviate each colour channel using one character instead of two identical characters. Browsers automatically expand these three-character colours into six by replicating the R, G, and B values. This technique saves a few bytes for each colour abbreviated with shorthand hex notation. Dave Parkinson
    • AJAX DEVELOPMENT Page 36 Start a new project in Aptana Studio called exercise5. With this exercise we will create a JavaScript program which will modify the styles on your document. Add a new HTML page called index.html. Add the following HTML code within the body section. <h1>JavaScript Styling</h1> <ul> <li class="odd" id="li1">List Item 1</li> <li class="even" id="li2">List Item 2</li> <li class="odd" id="li3">List Item 3</li> <li class="even" id="li4">List Item 4</li> </ul> <a href="#" id="tagStyle">Style by tag</a> <a href="#" id="classStyle">Style by class</a> <a href="#" id="idStyle">Style by ID</a> This will display the following: Dave Parkinson
    • AJAX DEVELOPMENT Page 37 Now add a JavaScript file to your project. Name the file convert.js and make sure you reference it in your web page. Add the following code to your JavaScript file: //executes the function DomReady() when the page has finished loading window.addEventListener('load', DomReady, false); /** * Adds "onclick" events to each of the link elements */ function DomReady(){ document.getElementById('tagStyle').addEventListener('click',tagStyle , false); document.getElementById('classStyle').addEventListener('click', classStyle, false); document.getElementById('idStyle').addEventListener('click',idStyle, false); } /** * When executed, this function will retrieve all "li" * html elements and give them all a 5 pixel margin. */ function tagStyle(e){ e.preventDefault(); var els = document.getElementsByTagName('li'); //gets ‘li’ elements for(var i = 0; i < els.length; i++){ //cycles through each element in the array els[i].style.margin = '5px'; } } This code will initially execute the function DomReady when the page has finished loading. The DomReady function adds ‘onclick’ events to each of the links on the web page (note that these event listeners could have been placed in a function following page load as we did previously). The function tagStyle runs when the link on the link on the web page is clicked. This function retrieves the ‘li’ HTML elements on the page into an Dave Parkinson
    • AJAX DEVELOPMENT Page 38 array of elements. It then cycles through each element in the array, giving each of them a 5 pixel margin. Try adding the two additional functions to the page classStyle and idStyle to your code. The function classStyle should retrieve the ‘li’ tags in the same way as the first function, but then should check the class of each element and if the class is odd it should set the background colour to Red and if it is even it should set the background colour to Blue. The function idStyle should use the getElementByID function to retrieve elements with a specific ID (ie ‘li1’, ‘li2’, ‘li3’, ‘li4’) and set their border styles to be 5 pixels wide with each border having a different colour. If you have time add further links to your document to add further style changes to the List Items. Dave Parkinson
    • AJAX DEVELOPMENT Page 39 Chapter 5 : MooTools JavaScript Framework 5.1 Introduction What is a Framework? Frameworks are commonly used in many programming languages, one of the most famous is the .NET framework released by Microsoft. A framework is a set of commonly used code and functions which can aid a programmer in his or her development of an application. Commonly used frameworks in JavaScript are MooTools, JQuery and Prototype. 5.2 MooTools MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API. More details on MooTools (including the download for the JavaScript library can be found at www.mootools.net . As well as the MooTools web site, further information on the use of MooTools can be found at www.mootorial.com 5.2.1 Elements MooTools has many functions to ease the manipulation and creation of XHTML elements. In native JavaScript, if we want to retrieve an element by its ID we would use document.getElementById(), however MooTools provides us with a very simple element Dave Parkinson
    • AJAX DEVELOPMENT Page 40 retrieval method which uses just one character: $. One of the many ways it can be used is as follows: //JavaScript native var div = document.getElementById('myDiv'); //mootools var div = $('myDiv'); Not only is it simpler to do, it also retrieves far more than just the element, but all the events and methods associated with that element. It is highly recommended you use that when working with MooTools. If you want to retrieve multiple elements, the double dollar ($$) is used. A $$ works in very similar ways as the $ function, however the $$ returns an array instead of a single elements. There are a variety of ways a $$ can be used: //retrieve elements by tag name var anchorEls = $$('a'); //retrieve elements by class named “myClass” var myClassEls = $$('.myClass'); //retrieve form elements where the atttribute “name” is //“username” var userNames = $$('input[name=username]'); Most XPath (XPath – XML Path Language, is a language for selecting nodes from an XML document) queries can be used to retrieve any set of elements from the DOM, and also CSS identifiers. Combinations can also be used: var els = $$('a .myClass', '#myDiv', 'a[href=/index.php]'); 5.2.2 Creating and Editing an Element If you want to create a new element, MooTools makes this process incredibly quick and easy using the Element constructor. //creates a new empty anchor element var myAnchor = new Element('a'); As simple as that! Of course we want to do more with it than just create it, so you can use a JavaScript 'options' object to create attributes, insert text nodes etc.. var myAnchor = new Element('a',{ 'href':'/index.php', 'class':'myClass', 'text':'take me home' //<-- notice no comma }); If an element is already created, and you want to add or change an option, this is simply done by using the set( ) method, which takes the parameters of option/attribute and value: myAnchor.set('class','myOtherClass'); Dave Parkinson
    • AJAX DEVELOPMENT Page 41 The set( ) method can also be used to change the 'text' of an element, however if you want to append the text, you can do that simply by using the appendText() method. //will change the text to “take me home please.” MyAnchor.appendText(' please.'); If you want to style an element, you can either set them when constructing an element, or change them later using a similar way to setting options. MooTools uses CSS styles to style elements. var myAnchor = new Element('a',{ 'href':'/index.php', 'class':'myClass', 'text':'take me home', 'styles':{ 'background-color':'#F00', 'border':'#0F0 solid 1px' } }); We can also set individual elements styles as follows: myAnchor.setStyle('padding','3px'); Finally, we will want to insert our newly created element into the DOM, and this is using the inject() function. This takes the element you want to inject into as a parameter: myAnchor.inject($('myDiv')); Further reading about elements and their construction and manipulation visit the MooTools documentation for this at: http://mootools.net/docs/Element/Element Particularly read up on the methods: 'set', 'get', 'inject', 'replaces', 'getFirst', 'getLast', 'adopt', 'erase' and 'destroy'. 5.2.3 Events Previously we have been using the addEventListener( ) function to assign events to elements whilst being unobtrusive. As we have explained before, there are compatibility problems with that method, and lack of flexibility. MooTools combats this by having it's own method called addEvent(). This takes 2 parameters: the type of event ('click', 'submit' etc..), and the function to execute on event (this can either be embedded or as a reference). This is very similar to the addEventListener( ) that you have used previously. $('myDiv').addEvent('click', function(e){ alert('you have clicked me!'); }); Also, when you want to initialise something at the start of the page (ie. After page load), the 'load' event is not really recommended to use, instead use 'domready'. For example if we wish to run a function called converter after a submit button is pressed as we did in example4 we can use the following code (note that unlike our previous JavaScript event listener, this code using MooTools will function in both Firefox and IE) Dave Parkinson
    • AJAX DEVELOPMENT Page 42 window.addEvent('domready',domReady); function domReady( ){ $('converter').addEvent('submit',converter); } Events can also be assigned in the creation of elements as well as follows: var myAnchor = new Element('a',{ 'href':'/index.php', 'class':'myClass', 'text':'take me home', 'styles':{ 'background-color':'#F00', 'border':'#0F0 solid 1px' }, 'events':{ 'click':myFunction //<-- no quotes because it's a function } }); function myFunction(e){ e.preventDefault(); alert(“I've also been clicked!”); } 5.2.4 Exercise 6 – Miles to Kilometre Converter using MooTools Start a new project called exercise6. Download the file mootools.js from the download section at www.mootools.net Download MooTools 1.2.4 (the Uncompressed version) and add it to your project. Edit the index.html file as shown below: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>New Web Project</title> Dave Parkinson
    • AJAX DEVELOPMENT Page 43 <script type="text/javascript" src="mootools.js"></script> <script type="text/javascript" src="mootest.js"></script> </head> <body> <div> <form method="post" action="#" id="converter"> <div> <label>Convert</label> <input name="val" type="text" /> <label>miles into kilometers</label> <br/> <input type="submit" value="convert" /> </div> <span id="result"></span> </form> </div> </body> Now add a JavaScript file to your project. Name the file convert.js Add the following code to your JavaScript file: window.addEvent('domready',domReady); function domReady(){ $('converter').addEvent('submit',converter); } function converter(e){ e.preventDefault(); $('result').set('text','The result is ' + performConvert(this.val.value)); } function performConvert(value){ var result result = value * 1.609; return result; } Test your program. You should see the following result: Note that when we use a different value to convert the result is output to the same position n the screen unlike when we tried to do this using DOM methods. Also the program now works equally well in Internet Explorer. Modify you index file to remove the line: <span id="result"></span> Dave Parkinson
    • AJAX DEVELOPMENT Page 44 Using MooTools try and create a new span element (called result) within your JavaScript and inject it into the correct place in the DOM. Then write to this element as above. Try and modify the styling of the element (e.g. change the background colour, the colour of the text, and place a black border around the text). 5.2.5 Exercise 7 – Calculator using MooTools Start a new project called exercise7. 5.2.6 MooTools Effects MooTools initially started off as an FX plugin for the framework Prototype, and therefore this FX class has been a main selling point of MooTools since it began. Primarily there are 2 main functions you need to be aware of: tween and morph. Tween creates a transition from one style value to another, while morph can do multiple values at the same time. Here is a list of some generic options which can be used in all FX objects (this has been extracted from the MooTools documentation): • fps - (number: defaults to 50) The frames per second for the transition. • unit - (string: defaults to false) The unit, e.g. 'px', 'em', or '%'. See Element:setStyle. • link - (string: defaults to ignore) Can be 'ignore', 'cancel' and 'chain'. 'ignore' - Any calls made to start while the effect is running will be ignored. (Synonymous with 'wait': true from 1.x) 'cancel' - Any calls made to start while the effect is running will take precedence over the currently running transition. The new transition will start immediately, cancelling the one that is currently running. (Synonymous with 'wait': false from 1.x) 'chain' - Any calls made to start while the effect is running will be chained up, and will take place as soon as the current effect has finished, one after another. • duration - (number: defaults to 500) The duration of the effect in ms. Can also be one of: Dave Parkinson
    • AJAX DEVELOPMENT Page 45 'short' – 250ms 'normal' - 500ms 'long' - 1000ms transition - (function: defaults to 'sine:in:out' The equation to use for the effect see Fx.Transitions. You do not need to necessarily know how to use all of these. Fx.Tween Tween allows a single style (css style) to be transformed from one value to another and is initialised by: var myFx = new Fx.Tween(element [,options]); “element” is the element that the effect is being applied to (either using the $( ), $$( ) or variable). The options are as stated above, but mostly can be just left as default. In order to start a transition, you use the .start( ) method which takes 3 arguments: the css style being manipulated, the starting value and the ending value. If no ending value is assigned, it makes the start value the end value, and the start value is the current state of that object's property. For example: myFx.start('height', 100, 400); //changes the height from 100px to 400px myFx.start('background-color','#f00'); //changes the background colour from whatever it is at the moment, to red The shorthand for doing this same function, is by using the tween( ) method from the Element object. $('elementId').tween('background-color','#ccc'); Fx.Morph The Morph effect works in exactly the same way as the tween effect, except it performs multiple transitions simultaneously. Instead of taking multiple parameters, the start( ) takes a single JavaScript object. var myFx = new Fx.Morph(element [,options]); myFx.start({ 'height': [100,400], //changes the height from 100 to 400 'background-color': '#00f' //changes background to blue }); Another way Morph can be used is to transition to an already existing style in CSS. myFx.start('.myClass'); //morphs to all the properties of the CSS class 'myClass' Again, like tween, there is a Morph element function, which operates in the same way as the start( ). Dave Parkinson
    • AJAX DEVELOPMENT Page 46 5.2.7 Example 8 - Styling Elements using MooTools Start a new project in Aptana Studio called exercise8. With this exercise we will recreate the JavaScript program we wrote in exercise 5 only this time we will use MooTools to modify the styles on your document. Add a new HTML page called index.html. Add the following HTML code within the body section (same as exercise 5). <h1>JavaScript Styling</h1> <ul> <li class="odd" id="li1">List Item 1</li> <li class="even" id="li2">List Item 2</li> <li class="odd" id="li3">List Item 3</li> <li class="even" id="li4">List Item 4</li> </ul> <a href="#" id="tagStyle">Style by tag</a> <a href="#" id="classStyle">Style by class</a> <a href="#" id="idStyle">Style by ID</a> This will display the following: Now add a JavaScript file to your project. Name the file moostyle.js and make sure you reference it in your web page. Add ‘click’ events to each of the links on the page as we did in the previous MooTools examples. Change the styling of the list items as we did previously but this time use MooTools tween to achieve the same effects. For example on the ‘Style by ID’ link you can change the style of the individual list items to add a coloured border as follows: $('li1').tween('border','5px solid #F00'); If we use the longhand method of writing this effect we can also set some of the generic MooTools effects: var myFx = new Fx.Tween($('li1'), { Dave Parkinson
    • AJAX DEVELOPMENT Page 47 transition:'bounce:in:out', duration: 'long' }); myFx.start('border','5px solid #F00'); This will have the effect of adding a border around the list element but will also add a bounce effect with a long duration. One of the advantages of MooTools is that we can use the $$ function to return the entire contents of an array. Hence by using $$ we can apply a tween to every element containing a particular tag. For example for the function attached to the link ‘Style by tag’ we can alter the style of all tags in a single command: $$('li').tween('margin','3'); MooTools also supports a mousewheel event that runs when the mousewheel is used. Add the following line to your domReady function: window.addEvent('mousewheel',styleall); This will run the function style all when the mousewheel is used : function styleall(e){ e.preventDefault(); $$('li').morph({ 'width':'300', 'border': '1px solid #ff0', 'margin':'0', 'background-color': '#999' }); This function uses the morph effect to change a number of styles on every list element. Use this program to try out further MooTools effects using tween and morph. 5.2.8 MooTools Class Although JavaScript is an object oriented language, it uses prototypes rather than classes. However, MooTools includes a “Class” class which emulates traditional classes, and is what MooTools is built on. It is set up the same as most MooTools objects, and uses the term “initialize” as the constructor. Classes are useful for when reusing code in different contexts. For example if we wished to write a class that would instantiate a form that contained several elements we could do so with the following code. var MyForm = new Class({ initialize: function(id){ this.form = new Element('form',{ 'id':id, 'method':post }); var div = new Element('div'); new Element('input',{ 'name':'name', Dave Parkinson
    • AJAX DEVELOPMENT Page 48 'value':'your name', 'type':'text' }).inject(div); new Element('input',{ 'type':'submit', 'value':'submit' }).inject(div); div.inject(this.form); }, returnForm:function(){ return this.form; } }); As you can see, classes use the “this” keyword to refer to that instance of the object (like with Java, PHP and most other object oriented languages). In this case “this.form” is a class variable, that can be retrieved by any method within the scope of the class, but variables such as “div” are local variables which only exist within the constructor. If we wish to use this class within our application we could use the following code to inject the form into a particular point within the DOM. var form1 = new MyForm('first'); //sets the id to 'first' form1.returnForm().inject($('formlocation')); An example of using a class in this fashion is shown in the handout (exercise 9) Dave Parkinson
    • AJAX DEVELOPMENT Page 49 Chapter 6 : XMLHttpRequest 6.1 Introduction XMLHttpRequest is a DOM API that can be used by JavaScript and other web browser scripting languages to transfer XML and other text data between a web server and a browser. The data returned from XMLHttpRequest calls will often be provided by back- end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats such as HTML, JSON or plain text. XMLHttpRequest is an important part of the AJAX web development technique, and it is used by many websites to implement responsive and dynamic web applications. Examples of web applications that make use of XMLHttpRequest include Google Maps, Windows Live's Virtual Earth, Facebook, and many others. The XMLHttpRequest object is a very important tool for web developer’s, because you can: • Update a web page with new data without reloading the page • Request data from a server after the page has loaded • Receive data from a server after the page has loaded • Send data to a server in the background The XMLHttpRequest object is supported in all modern browsers. 6.2 Using the XMLHttpRequest object Because of differences in the implementation of the XMLHttpRequest object in different browsers the code for using the XMLHttpRequest object can be quite complex as it needs execute different paths dependent upon the browser. In order to read a file from a server it needs to go through the following stages: 1. Create an instance of the XMLHttpRequest object 2. Send a Request - Consists of three components (a) The onreadystatechange event handler (b) The open method (c) The send method 3. Receive a Response We will be using the XMLHttpRequest object with the MooTools framework and will not need to know the full details of the code. 6.3 Data Formats Dave Parkinson
    • AJAX DEVELOPMENT Page 50 Ajax is language agnostic. It does not matter what server side language you use. However, when you are requesting data from the server that data must be formatted in a way that the browser can understand. The server side programming language of choice must return data in one of three ways: XML, JSON or HTML. 6.3.1 XML XML is a universal standard for storing, organising, processing and communication of information. Since its introduction in 1996 XML has played an increasingly important role in databases, word processing and distributed computing over the internet. Given XML is a primarily text based standard it can be trusted to pass information through security firewalls between a wide range web based and local applications. XML stands for Extensible Markup Language. You have already used the Hypertext Markup Language (HTML) for displaying information on the web using standard tags that can hence parsed by Web Browsers and Word Processors. For example… <head>My Web Page</head> <body> <h1>My Page</h1> <image src=”Me.gif”/> This page is about me. </body> However the type of information and user interactivity offered by HTML is limited to what is offered by current set of standard tags available. XML is quite different from HTML in that XML is a meta-language, i.e. it’s used to define new tags to structure information or specify behaviour. Its primary role is data organisation – not displaying web pages. Here is an example of a simple XML document called daveparkinson.xml: <?xml version="1.0" encoding="utf-8"?> <person> <name>Dave Parkinson></name> <phone>0161 2954476</phone> <email>d.parkinson@salford.ac.uk</email> </person> The first line is an XML declaration stating the version of XML being used. Everything after that is contained within tags. Each set of tags denotes an element. The name of the element is contained within the opening and closing tags. The value of an element is also contained within the opening and closing tags. It is important to note that XML does not do anything, it is a means of storing data, not manipulating it. 6.3.2 JSON Dave Parkinson
    • AJAX DEVELOPMENT Page 51 JSON, which stands for JavaScript Object Notation, is a lightweight alternative to XML. Anything that can be stored in XML can be stored in JSON. This method of storing data is actually part of JavaScript and hence JSON data is stored in a .js file. If we want to set up the same information in a file daveparkinson.js as we did with the XML file we can use the following: {"person":{ "name":"Dave Parkinson", "phone":"0161 2954476", "email":"d.parkinson@salford.ac.uk" } } This is called an object literal. Values are assigned using colons instead of equals signs. Each assignment is separated with a comma. 6.3.3 HTML If you are sending data as XML or JSON, you need to convert it into HTML before displaying it in a web browser. This extra step can be avoided if data id sent in HTML to begin with. If we wish to sent contact details back as in the previous examples we could do so using HTML in a text file For example we could include the following data in a file called daveparkinson.html <a href="mailto:d.parkinson@salford.ac.uk">d.parkinson@salford.ac.uk</a> Technically this is not an HTML file as it does not have a doctype declaration, or a head and body element. It is more accurate to call this a fragment or a snippet of HTML. 6.4 MooTools Request The Request class is used for asynchronous requests to the server (ie. Ajax), and greatly simplifies the XHR request procedure. The class we will be using in this is the Request.JSON extension, which automatically parses JSON objects and arrays on return. This is useful because even though JSON is less readable to a human than XML, it is smaller overheads (as in filesize) and also is able to be manipulated by JavaScript far more easily. It is easily initialised by the line: var myRequest = new Request.JSON(options); “options” contains many different options that a progammer can use, some of them are required for the request to work, but others are merely very useful. Here's an overview of some of the options that are available: • url : contains a string URL for the page that will perform the Ajax request (required). • method : the method that is used to send the data (post or get). Defaults to post. Dave Parkinson
    • AJAX DEVELOPMENT Page 52 • onSuccess : this is a function that is run if the request is successful. Note this does not mean the server side processing has been performed correctly, it just means that the page has responded with a valid message. The function contains 2 arguments: responseJSON (e.g. the JSON array) and responseText (although the latter is not needed if it's a pure JSON return). • onFailure : Fired if the Ajax request fails. • onComplete : this function is fired when the request has been completed, regardless of whether it was successful or not. • async : Takes a boolean value, if set to false the request will be got synchronously rather than asynchronously, thus meaning that the program will freeze until the request has completed. This defaults to “true”. example: var myRequest = new Request.JSON({ url:'page.php', onSuccess: function(json){ json.each(function(jobject){ … }); }, onFailure: function(){ alert('Ajax request failed'); } }); myRequest.send(data); The data that can be sent can be in the form of a JavaScript object, querystring or even a form element: myRequest.send('name=rick&number=55242'); myRequest.send({'name':'rick','number':'55242'}); If this was to be added to the class above, we can just send the entire form object. var MyForm = new Class({ initialize: function(id){ this.form = new Element('form',{ 'id':id, 'method':post }); var div = new Element('div'); new Element('input',{ 'name':'name', 'value':'your name', 'type':'text' }).inject(div); new Element('input',{ 'type':'submit', 'value':'submit' }).inject(div); div.inject(this.form); }, Dave Parkinson
    • AJAX DEVELOPMENT Page 53 returnForm:function(){ return this.form; }, makeRequest:function(){ new Request.JSON({ url:'page.php', onSuccess: function(json){ json.each(function(jobject){ … }); }, onFailure: function(){ alert('Ajax request failed'); } }).send(this.form); } }); The above will create and return a new form (as before), and send the contents of the form to the server. Alternatively, you can use .get( ) and .post( ) instead of .send( ), which send the data via a querystring or post respectively. The arguments for these methods are the same as send( ). 6.4.1 Example 10 – Reading a JSON file using MooTools Start a new project in Aptana Studio called exercise10. With this exercise we will read a JSON file. Add a new HTML page called index.html. Add the following HTML code within the body section. <body> <h1>Staff List</h1> </body> Create a new file called jsonarray1.txt and add the following data: [ {"name":"Dave Parkinson", "email":"d.parkinson@salford.ac.uk", "phone":"0161 295 4476"}, {"name":"Dave Eustace", "email":"d.eustace@salford.ac.uk", "phone":"0161 295 5321"}, {"name":"Rick Ogden", "email":"r.l.ogden@salford.ac.uk", "phone":"0161 295 5242"} ] This array contains three JavaScript Objects and each object contains three properties (i.e. name, email and phone) Add the motools.js file to your project and reference it in your web page as per the previous examples. Dave Parkinson
    • AJAX DEVELOPMENT Page 54 Now add a JavaScript file to your project. Name the file moojson.js and make sure you reference it in your web page. Add the following JavaScript code: window.addEvent('domready',domReady); function domReady(){ var req = new Request.JSON({ url:'jsonarray1.txt', onSuccess:success }); req.send(); } function success(jarray){ jarray.each(function(staff){ var mydiv = new Element('div'); var pname = new Element('p',{ 'text':'name: ' + staff.name }); var pemail = new Element('p',{ 'text':'email: ' + staff.email }); var pphone = new Element('p',{ 'text':'phone: ' + staff.phone }); pname.inject(mydiv); pemail.inject(mydiv); pphone.inject(mydiv); mydiv.inject($$('body')[0]); new Element('br').inject(mydiv,'after'); }); } This code functions as follows: 1. window.addEvent('domready',domReady); This event listener runs the function domReady once the page is fully loaded. 2. function domReady(){ var req = new Request.JSON({ url:'jsonarray1.txt', onSuccess:success }); req.send(); } The function domReady uses the request class to raise an asynchronous request to the server to read the contents of the file jsonarray1.txt. It returns the data in a JSON array. 3. function success(jarray){ jarray.each(function(staff){ var mydiv = new Element('div'); var pname = new Element('p',{ 'text':'name: ' + staff.name }); var pemail = new Element('p',{ Dave Parkinson
    • AJAX DEVELOPMENT Page 55 'text':'email: ' + staff.email }); var pphone = new Element('p',{ 'text':'phone: ' + staff.phone }); pname.inject(mydiv); pemail.inject(mydiv); pphone.inject(mydiv); mydiv.inject($$('body')[0]); new Element('br').inject(mydiv,'after'); }); } On successful completion of the JSON Request the function success is called with the data being contained in the array jarray. JavaScript does not natively support foreach loops, and because of this MooTools has implemented a way of doing it by using the each( ) method. It can work with any type of array (whether it's an array of strings, JSON, Elements etc..), and can be used to cycle through it with ease. There is no need to know beforehand how long the array is. The above code cycles through each item in the JSON array and for each item in the array generates a new div element, and three p elements to contain the name, email and phone. The p elements (containing the JSON data) are injected into the div element which is in turn injected into the body of the document. Between each array item a br element is injected after the div. Run the program. Try changing the styling of the elements to improve the output. Dave Parkinson
    • AJAX DEVELOPMENT Page 56 Chapter 7 : Accessing a MySQL Database 7.1 Introduction In the previous exercise we have seen how we can retrieve data from a JSON file using AJAX (and MooTools). In a real world situation the data we wish to retrieve will typically be in a database (e.g. MySQL). In this exercise we will examine how we can retrieve data from a MySQL database and display it on our web page. As we will be using PHP to retrieve the data from the MySQL database all our files will have to run on a PHP enabled web server. We can do this without having to upload our code to the web by installing a local web server on our PC. In order to run your code locally on your PC we will be using XAMPP for Windows. XAMPP is an easy to install Apache Web Server distribution containing MySQL, PHP and Perl. All these products are Open Source and free to install. XAMPP is available for Microsoft Windows, Linux, Solaris, and Mac OS X, and is mainly used for web development projects. XAMPP requires only one zip or exe file to be downloaded and run, and little or no configuration of the various components that make up the web server is required. XAMPP is regularly updated to incorporate the latest releases of Apache/MySQL/PHP and Perl. One of the major advantages of XAMPP is that it allows you to install your development environment onto a pen drive which can then be moved between different PC’s enabling you to work on your PHP project in any PC lab or on your home PC without changing your configuration. We will be setting up our development environment on a pen drive with 1 Mb of free memory available (alternatively you could set up on the D: drive on the lab PC’s -note the environment is too large to fit on the F: drive). To install XAMPP on your pen drive go to http://www.apachefriends.org/en/xampp.html and select XAMPP for Windows. Scroll down to the XAMPP Windows (Basic Package and select the EXE file (Self- extracting RAR archive) as shown below: Dave Parkinson
    • AJAX DEVELOPMENT Page 57 Run the xampp-win32-1.7.3.exe file and when prompted select the path to install to point to your pen drive (e.g. e:). This will install a number of files and directories under the xampp directory on you pen drive as shown below: Note that within the directory structure we have a directory called htdocs. Any files or directories placed within htdocs will behave as if they have been uploaded onto an external web server. In order to test your development environment you need to run the file xampp- control.exe found in your xampp directory. Dave Parkinson
    • AJAX DEVELOPMENT Page 58 Start the services you require (for Web Server just start the Apache service). After Apache starts, open the URL http://localhost/index.php and examine all of the XAMPP examples and tools. If you have problems starting the Apache service on your home PC there are several possible problems. Initially you should run Port_Check from the XAMPP control panel with Apache stopped. You should see the following: If you start any of the services you will see the port status changed to SYSTEM. If the port status is not free when the services are not started then you have a problem. Likely causes are: 1. You are running Microsoft IIS web server locally on your machine (you must disable this as only one web server can be used in your PC) 2. You are running a local version of MySQL (remove this as XAMPP adds its own version of MySQL) 3. You are running some other program using the required ports (the usual problem will be on Port 80). The likely candidate will be a peer-to-peer application. For example many online TV services (i.e. SKY Player, ITV Player, 5 on demand) all uses the Kontiki peer- to-peer network to share TV programmes. This uses port 80 and will stop the Apache service working. In order to run Apache you need to start Task Manager, go to Processes, then Show Processes from all Users, and end the KService service. In order to restart this service and use your Sky Player you will need to restart your computer which will automatically restart the service. Another way of controlling your TV access from the PC is install the free program TV On-Demand. This program (available from http://odmonitor.blogspot.com/ ) allows you to launch various TV services alongside allowing you to Stop Sharing the TV data with other users via Kontiki. This effectively allows you to turn Kontiki services On and Off allowing you to then use the Apache Web Server. 7.2 Exercise 11 - Accessing data from a MySQL Database Dave Parkinson
    • AJAX DEVELOPMENT Page 59 In this exercise we are going to setup a MySQL database to hold a simple guestbook (containing a name and a comment). We are then going to develop separate web pages to read this information, insert new information, edit the information, and delete individual rows of information. 7.2.1 Setting up a MySQL Database MySQL is a database engine. In order to create individual databases and populate them with tables and data with must use a program that provides an interface to MySQL (e.g. phpMyAdmin). phpMyAdmin is an open source tool written in PHP intended to handle the administration of MySQL over the World Wide Web. It can perform various tasks such as creating, modifying or deleting databases, tables, fields or rows; executing SQL statements; or managing users and permissions. It is included with most providers of MySQL databases and is also included on the locally hosted version of MySQL installed using XAMPP. To run MySQL on the PC’s in the lab you need to run the file mysql_start.bat from within the xampp directory on your pen drive. To stop MySQL you run mysql_stop.bat (Note that on your home PC you start MySQL by clicking on the MySQL button in the XAMPP Control Panel – note that this does not work on the University PC’s) You can open phpMyAdmin from within your web browser by going to http://localhost/phpmyadmin This will open phpMyAdmin in your default browser as shown below: You can then create a new database called test: Dave Parkinson
    • AJAX DEVELOPMENT Page 60 Now create a table called myguestbook containing three fields: Set up the following field names and also set the field types as shown below: Set the index fields for the id field to PRIMARY (makes the id field the primary key). Also set the id field to auto increment. Select Insert to add a record: Add a number of records to populate the database as shown below: Dave Parkinson
    • AJAX DEVELOPMENT Page 61 7.2.2 Reading from a MySQL Database In order to simplify the process of reading and writing to the MySQL database you have created, we have written a number of files that perform the process of reading and writing to your database via JSON files. The following file can be downloaded from Blackboard. exercise11.zip Unzip this file and into htdocs directory under the XAMPP directory on your pen drive. Within Aptana select Switch Workspace from within the file menu and then select browse to select the htdocs directory under xampp as your workspace: In the file menu navigate to your exercise11 directory under htdocs. Select the directory and right click on it. From the drop down menu select Promote to Project. Exercise11 should now appear in your projects folder as shown below: Dave Parkinson
    • AJAX DEVELOPMENT Page 62 This directory now contains all the files needed to read, insert, edit and delete data from your MySQL database. The files downloaded from Blackboard perform the following functions: class.Database.php This file is an open source PHP program allowing you to execute SQL queries into a MySQL database. YOU DO NOT NEED TO EDIT THIS FILE. class.Guestbook.php This a program written by Rick Ogden which sets up the connection to your database table and gets data from the MySQL database (via class.Database.php) and puts the information into a JSON array. It effectively interfaces between database class and the control page. YOU DO NOT NEED TO EDIT THIS FILE. control.php This a program written by Rick Ogden which creates a number of functions that can be used to access your guestbook database table. YOU NEED TO EDIT THIS FILE TO SPECIFY YOUR INDIVIDUAL GUESTBOOK TABLE AS SHOWN BELOW: $guestbook = new Threaded_GuestBook(null,'guestbook'); This program provides 5 functions: insertPost – adds a new row to your database table editPost – edits an individual row based on the row id field getSinglePost – gets a single post based on the row id field getPage – gets an array of posts. If no parameters are specified it returns the 10 most recent posts. You can also specify an offset value to retrieve earlier posts. removePost – deletes an individual row based on the row id field Dave Parkinson
    • AJAX DEVELOPMENT Page 63 All these functions work with any number of fields specified within your database table (you are NOT limited to the 2 fields shown in this example) mootools.js This is the MooTools JavaScript library file we have used earlier All the other files are the HTML and associated JavaScript files to create four separate web pages to read, insert, edit and delete messages into the guestbook (note that we need to call these .php files in order to add code to control caching when we run the program). readposts.php – this is effectively a HTML file which when used in conjunction with its associated JavaScript file, read.php, will read and display up to 10 messages from the guestbook <?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>My Guestbook</title> <script type="text/javascript" src="js/mootools.js"></script> <script type="text/javascript" src="js/read.php"></script> </head> <body> <div> <h1>My Guestbook</h1> <div id="commentList"> </div> </div> </body> </html> read.php – JavaScript file used in conjunction with readposts.php <?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> var guestbook; window.addEvent('domready', function(){ guestbook = new GuestBook(); Dave Parkinson
    • AJAX DEVELOPMENT Page 64 }); var GuestBook = new Class({ initialize: function(){ var req = new Request.JSON({ url: 'control.php?action=getPage', onSuccess: this.success }).send(); }, success: function(jArray){ jArray.each(function(post){ var post = new PostItem(post.id, post.name, post.comment); post.display().inject($('commentList')); }, this); } }); var PostItem = new Class({ initialize: function(id, name, comment){ this.id = id; this.name = name; this.comment = comment; }, display: function(){ var cont = new Element('div',{ 'class':'postItem', 'id':'post'+this.id }); var title = new Element('h3',{ 'class':'postTitle', 'text':this.name + ' says...' }); var comment = new Element('p',{ 'class':'postComment', 'text':this.comment }); title.inject(cont); comment.inject(cont); return cont; } }); Test you code by running the new page: http://localhost/exercise11/readposts.php You should see the following: Dave Parkinson
    • AJAX DEVELOPMENT Page 65 7.2.3 Inserting into a MySQL Database Now we can read a database we can also use the prewritten files to insert a new entry into our guestbook. insertpost.php – this is effectively a HTML file which when used in conjunction with its associated JavaScript file, insert.php, will insert a new entry into the guestbook <?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>My Guestbook</title> <script type="text/javascript" src="js/mootools.js"></script> <script type="text/javascript" src="js/insert.php"></script> </head> <body> <div> <h1>My Guestbook</h1> <form id="newComment" action="#"> Dave Parkinson
    • AJAX DEVELOPMENT Page 66 <div><label>Name: </label> <input type="text" name="name"/> </div> <div><label>Comment: </label> <textarea name="comment"></textarea> </div> <div><input type="submit" value="submit"/></div> </form> </div> </body> </html> insert.php – JavaScript file used in conjunction with insertpost.php <?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> window.addEvent('domready',domReady); function domReady(){ var guestbook = new GuestBook(); } GuestBook = new Class({ initialize: function(){ $('newComment').addEvent('submit', this.addComment); }, addComment: function(e){ e.preventDefault(); var req = new Request({ url:'control.php?action=insertPost', onSuccess:commentAddSuccess }).post(this); function commentAddSuccess(idNo){ new Element('span',{ 'text':'inserted item ' + idNo }).inject($('newComment')); } }, }); Test your new page. http://localhost/exercise11/insertpost.php Your program should look like this: Dave Parkinson
    • AJAX DEVELOPMENT Page 67 7.2.4 Editing an entry in a MySQL Database Now we can use the prewritten files to edit an entry into our guestbook. editpost.php – this is effectively a HTML file which when used in conjunction with its associated JavaScript file, edit.php, will edit an entry into the guestbook based on its id. <?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>My Guestbook</title> <script type="text/javascript" src="js/mootools.js"></script> <script type="text/javascript" src="js/edit.php"></script> </head> <body> <div> <h1>My Guestbook</h1> <form id="newComment" action="#"> <div><label>ID: </label> <input type="text" name="id"/> </div> <div><label>Name: </label> <input type="text" name="name"/> </div> <div><label>Comment: </label> <textarea name="comment"></textarea> </div> <div><input type="submit" value="submit"/></div> </form> </div> </body> </html> Dave Parkinson
    • AJAX DEVELOPMENT Page 68 edit.php – JavaScript file used in conjunction with editpost.php ?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> window.addEvent('domready',domReady); function domReady(){ var guestbook = new GuestBook(); } GuestBook = new Class({ initialize: function(){ $('newComment').addEvent('submit', this.addComment); }, addComment: function(e){ e.preventDefault(); var req = new Request({ url:'control.php?action=editPost', onSuccess:commentAddSuccess }).post(this); function commentAddSuccess(){ new Element('span',{ 'text':'edited item ' }).inject($('newComment')); } }, }); Test your new page. http://localhost/exercise11/editpost.php Your program should look like this: Dave Parkinson
    • AJAX DEVELOPMENT Page 69 7.2.5 Deleting an entry in a MySQL Database Now we can use the prewritten files to delete an entry into our guestbook. deletepost.php – this is effectively a HTML file which when used in conjunction with its associated JavaScript file, delete.php, will delete an entry into the guestbook based on its id. <?php <?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>My Guestbook</title> <script type="text/javascript" src="js/mootools.js"></script> <script type="text/javascript" src="js/delete.php"></script> </head> <body> <div> <h1>My Guestbook</h1> <form id="newComment" action="#"> <div><label>ID: </label> <input type="text" name="id"/> </div> <div><input type="submit" value="submit"/></div> </form> </div> </body> </html> delete.php – JavaScript file used in conjunction with deletepost.php ?php //Set no caching header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> window.addEvent('domready',domReady); Dave Parkinson
    • AJAX DEVELOPMENT Page 70 function domReady(){ var guestbook = new GuestBook(); } GuestBook = new Class({ initialize: function(){ $('newComment').addEvent('submit', this.addComment); }, addComment: function(e){ e.preventDefault(); var req = new Request({ url:'control.php?action=removePost&id=' + this.id.value, onSuccess:commentAddSuccess }).send(); function commentAddSuccess(){ new Element('span',{ 'text':'deleted item' }).inject($('newComment')); } }, }); Test your new page. http://localhost/exercise11/deletepost.php Your program should look like this: Dave Parkinson
    • AJAX DEVELOPMENT Page 71 7.2.6 Extending Exercise 11 to include multiple threads Now we can use the prewritten files to include multiple threads within our guestbook. The use of threads requires an additional database table and the addition of an extra field to the existing database table (myguestbook) within the test database. The new table (e.g. threadtable) requires two fields: id and name. id should be set to the primary key and should be an auto incrementing integer. name is the name of the thread and should be a varchar. The original table (myguestbook) requires the addition a new field called thread. This is a foreign key that refers to the id of whichever thread it is part of. This field should be set to index. To use this additional functionality you need edit the control.php file as follows: $guestbook = new Threaded_GuestBook('threadtable','guestbook'); The new table (threadtable which replaces the original null) is the name of the table created above. The file control.php contains a number of additional functions that enable you to use threads within your guestbook. This program provides 5 additional functions for use with threads: getThreadList – retrieves a list of all the threads as a JSON array getThread – retrieves all the posts within a single thread. This is done in the same manner as the removePost and you need to provide the url information as follows e.g. 'control.php?action=getThread&id=5’ (this will retrieve all posts from the tread with id 5 as a JSON array). createThread – creates a thread in the same manner as insertPost and returns the id. renameThread – renames a thread in the same manner as editPost. deleteThread – deletes the thread and all the posts within the thread in the same manner as removePost. The new functionality has been added to the Exercise11.zip download available from Blackboard. Dave Parkinson