csci 4131: internet programming class 10: april 15, 2008

40
Jamshid A. Vayghan, Ph.D. 1 CSci 4131: Internet Programming Class 10: April 15, 2008 Jamshid A. Vayghan, Ph.D. Spring 2008

Upload: sampetruda

Post on 19-Jan-2015

1.430 views

Category:

Documents


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 1

CSci 4131: Internet Programming

Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D.Spring 2008

Page 2: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 2

Today’s Agenda

Ajax Frameworks & Libraries (Appendix B)JSON (Chapter 11)Connection to DBMS (Chapter 12)

Page 3: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 3

Ajax Resources—Frameworks and Libraries (Client & Server sides)

A framework includes programs, libraries, and a scripting language, and it usually includes an underlying structure for organizing projects.

A framework such as Ruby on Rails offers a comprehensive programming environment, while a library such as Scriptaculous specializes in visual effects.

A library is a collection of functions that are easy to access because they're gathered together in one location.

Page 4: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 4

Client side

Page 5: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 5

Prototype

Prototype is a general-purpose JavaScript library that extends the JavaScript language to include more object-oriented programming capabilities. You can download Prototype from the Prototype site at http://www.prototype.conio.net/. You can access the Prototype library by including a script tag in your page that references the location of prototype.js on your Web server:

<script type="text/javascript" src="prototype.js"></script>

Page 6: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 6

Prototype: Object.extend

One of Prototype's most powerful functions is Object.extend, which allows a second object to "extend" the first object by adding the second object's properties and methods to the first object:myObj = {name: "reservation", required: "yes"}; myObj2 = {deposit: "one night"};Object.extend(myObj, myObj2);

Page 7: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 7

Prototype includes a built-in Ajax object that can be used to make cross-browser XMLHTTP requests.

To create an XMLHTTP request to ajax.php, and to call a function named process when the request is completed, you could use the following code: new Ajax.Request('ajax.php', (method: 'get', onComplete: process});

Additional information:http://en.wikipedia.org/wiki/Prototype_JavaScript_FrameworkDownload prototype.js from http://prototypejs.org/

Page 8: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 8

Prototype: DOM manipulation methods

It provide some DOM manipulation methods such as the $(), $$().

The $ method is similar to getElementById(), but it takes it a step further. You can pass more than one id value to $() and return an array with all the elements with any of the passed id values.

The $$() method, introduced in Prototype 1.5, enables you to select elements using CSS selector syntax.

For example, the following code returns an array of all select elements contained in the form whose id value is contactInfo:

var mySelects = $$("#contactInfo select");You can also use $$() to access all elements with a particular class name. You could use the following to access all paragraphswith the class name red:

var myPara = $$("p.red");

Page 9: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 9

Scriptaculous

Scriptaculous is a collection of user-interface components that is built on top of the Prototype library. You can download Scriptaculous at http://www.script.aculo.us/downloads.

You can access all of Scriptaculous by adding the following code to the head section of your page once you've copied prototype.js and scriptaculous.js to your Web server:

<script src="javascripts/prototype.js" type="text/javascript"></script><script src="javascripts/scriptaculous.js" type="text/javascript"></script>

You can also include only the scripts you need by specifying them in a comma-separated list. The five scripts are builder, effects, dragdrop, controls, and slider.

<script src="javascripts/prototype.js" type="text/javascript"></script> <script src="scriptaculous.js?load=effects,dragdrop" type="text/javascript"></script>

Page 10: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 10

DojoDojo is a powerful JavaScript library that includes a group of core libraries for working with HTML, JavaScript, and the DOM, as well as libraries for data structures, RPC, JSON, animation, drag-and-drop, validation, cryptography, math, and an extensive collection of widgets. You can download one of many special editions of Dojo (for example, an Ajax edition, event edition, or widget edition) from the main Dojo site at http://www.dojotoolkit.org.Dojo is made up of packages including packages for Ajax, animation, drag-and-drop, events, and widgets. Once you've copied dojo.js to your Web server, you can access a Dojo package from your page by including a script element with the URL for the dojo.js file, also known as the Dojo bootstrap:

<script type="text/javascript" src="dojo.js"></script> Next, add another script element that specifies which Dojo packages you're using in the page:<script type="text/javascript">

dojo.require("dojo.event.*"); dojo.require("dojo.widget.*");

</script>

Page 11: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 11

Yahoo! User Interface Library

The Yahoo! UI library (YUI) is a collection of utilities and controls. Originally created by Yahoo! for its own use, it is now available as Open Source. The entire library can be downloaded at http://www.sourceforge.net/projects/yui. Documentation and examples are included in the download. You can also download a zip file of Yahoo! Cheat Sheets (http://www.developer.yahoo.com/yui/docs/assets/yui-0.11-cheatsheets.zip) that includes a cheat sheet for each library that details the methods, properties, and syntax for that library.Each of the Yahoo libraries depends on the small (4K) yahoo.js file. Once you've downloaded the library and uploaded it to your Web server, you can access any of the YUI libraries from your pages.

To reference a library from your page, include both yahoo.js and the specific library you want to use. For example, to use the connection library, include these script tags in the head section of your page:

<script type="text/javascript" src="yahoo.js"></script> <script type="text/javascript" src="connection.js"></script>

Page 12: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 12

MochiKitMochiKit calls itself a "lightweight JavaScript library."

It's available as a free-standing download at http://www.mochikit.comand is also bundled with the Python-based TurboGears framework.

MochiKit is a collection of 14 modules. The MochiKit.Base module is the foundation for the rest of the modules. MochiKit.Base includes functions for manipulating objects and arrays, comparison functions, and functions for JSON serialization and evaluation. MochiKit.Base is similar to the Python standard library.

MochiKit also includes modules for asynchronous tasks, DOM manipulation, event handling, and logging, as well as modules for effects and CSS (including drag-and-drop, CSS manipulation, sortableobjects, and visual effects).

MochiKit methods are well documented, but unless you're well versed in functional programming techniques, you'll likely find it difficult to use.

Page 13: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 13

Server Side

Page 14: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 14

Ruby on Rails

Ruby on Rails is a framework for rapid development of database-driven Web applications based on the Ruby programming language. Ruby is an object-oriented programming language that originated in Japan in the early 1990s and became popular worldwide as English documentation of its features became available. Rails was developed by the 37signals group (http://www.37signals.com) when they created Basecampsoftware for project management online.Rails provides Ajax support through the Prototype library, whichis included in the Rails installation. You make Prototype accessible by adding this code to the head section of your web page:

<%= javascript_include_tag "prototype" %> Rails includes helper functions specific to Ajax, including link_to_remote(), form_remote_tag(), and observe_field().

Page 15: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 15

Atlas (ASP.NET Ajax)ASP.NET Ajax (formerly known in earlier versions as Atlas) is a Microsoft framework (http://www.ajax.asp.net) designed for Ajax application development by ASP.NET developers, although the Microsoft Ajax library is also available as a standalone library. ASP.NET Ajax contains JavaScript libraries and server components.Client-side features of this framework include extensions to JavaScript (such as namespaces and object serialization) and extensions to JavaScript's Array, Boolean, Error, Number, Object, and String objects.

For more details on these extensions see http://www.ajax.asp.net/docs/ClientReference/JavascriptTypeExtensions/default.aspx.These libraries also feature user-interface components and controls such as an auto-completion text box.

Server-side features of this framework include web services that integrate with Ajax applications, server controls that generate JavaScript code, and integration with Visual Studio. The asynchronous communication model includes the following:

Data formats including XML, JSON, string, and custom formats, depending on the specified content typeAn XmlHttpExecutor componentJavaScript Web service proxies

Page 16: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 16

JavaScript Object Notation: JSON

Page 17: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 17

JavaScript eval() Function

The eval() function evaluates a string and executes it as if it was script code.

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_eval

Page 18: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 18

Data Transmission Format between Client & Server

What criteria do you use to select the right format for data transfer between client & server?How many forms can data be transformed between server & client?

Page 19: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 19

JSON

Douglas Crockford has created an alternative data transmission format named JavaScript Object Notation (JSON).

One of the advantages of using JSON for data transmission is that JSON is actually JavaScript—it's a text format based on a subset of JavaScript object-literal syntax from the third edition of ECMAScript. This means you can use responseText to retrieve JSON data from a server,

and then you can use JavaScript's eval() method to convert a JSON string into a JavaScript object.

You can then easily extract the data from this object using additional JavaScript—and no DOM manipulation is needed.

Page 20: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 20

JSON Syntax

JSON consists of two data structures:Objects—An unordered collection of name/value pairsArrays—An ordered collection of values

There are no variables or other control structures in JSON. It'sdesigned solely for transmitting data.

JSON syntax is based on JavaScript syntax for object literals and array literals.

When you use literals, you include the data itself, rather than an expression that generates the data.

For example, in the following code block, the value that's assigned to the variable x is a literal (15), while the value that's assigned to the variable y is an expression (3*x) that must be evaluated before the assignment is complete.

var x = 15; var y = 3 * x;

Page 21: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 21

JSON Data TypesJSON data structures can include any of the following types of data:

StringNumberBoolean value (true/false)null ObjectArray

JSON strings must be double-quoted.

They use standard JavaScript escape codes and add a backslash before the following characters:

“ (quotation marks)b (backspace)n (new line)f (form feed)r (carriage return)t (horizontal tab)u (plus 4 digits for a Unicode character)\ (backslash)/ (forward slash)

For example, to represent the string I feel “funny”, you escape both sets of quotation marks around the word funny: "I feel \"funny\""

Page 22: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 22

JavaScript objects can be defined using an object constructor or an object literal. To define a new object with a constructor, you use the Object constructor function with the new keyword:var member = new Object();

Then you can add properties to the object using dot notation.

member.name = "Jobo"; member.address = "325 Smith Rd"; member.isRegistered = true;

Then you can add properties to the object using dot notation.

member.name = "Jobo";member.address = "325 Smith Rd";member.isRegistered = true;

You can create the same object more efficiently by using an object literal.

var member ={name: "Jobo",address: "325 Smith Road",isRegistered: true};

JSON doesn't use constructors, only literals. The following code shows the member object formulated as JSON text:

{"name": "Jobo","address": "325 Smith Road","isRegistered": true

}

Page 23: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 23

Array Literals

JavaScript arrays can also be created using a constructor or using an array literal. To define a new array with a constructor, you use the Array constructor function with the new keyword.

var myArray = new Array(); Then, you can add members to the array using square brackets and an index value that indicates the position in the array.

myArray[0] = 1218; myArray[1] = "Crawford" myArray[2] = "Drive";

You can create the same object more efficiently using an array literal.

var myArray = [1218, "Crawford", "Drive"]; The following code shows this array formulated as JSON text:

[1218, "Crawford", "Drive"]

Page 24: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 24

JSON Parser

You can use a JSON parser to create JSON text from objects and arrays,

and to create objects and arrays from JSON text.

A JSON parser is provided on the JSON site at http://www.json.org/json.js.

You can copy this JavaScript file and reference it in your page by including this code in the head section of the page:

<script type="text/javascript" src="json.js"></script>

It defines two functions:toJSONString() parseJSON()

Page 25: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 25

toJSONString() methodThe toJSONString() method is added to the JavaScript Object and Array definitions, and it enables you to convert a JavaScript object or array to JSON text. The object or array doesn't need to be preformulated as a literal in order to use this method. For example, the following code for the member object uses the Object constructor:

<script type="text/javascript"> var member = new Object(); member.name = "Jobo"; member.address = "325 Smith Rd"; member.isRegistered = true; member = member.toJSONString();alert("The member object as a JSON data structure: \n" + member);

</script>

Page 26: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 26

Data Transmission FormatsEither JSON or XML can be used for data transmission in Ajax applications.

The major factor in choosing a data transmission format is the type of data you want to transmit. XML has a much more complex structure than JSON, and it can be used for transmitting almost any type of data. Many desktop applications (such as Microsoft Word, Excel, and Access) now allow you to import and export data as XML;

however, JSON's simple data structure may be all you need to transmit the data in your Ajax application, and using JSON has several advantages:

JSON is JavaScript.—JSON text can be easily converted into JavaScript objects and arrays using JavaScript's eval() method. You can then extract the data from the server response using JavaScript. This means JSON is especially easy to use if you're already familiar with JavaScript.

JSON is typed.—A JSON object already has a JavaScript datatype: string, number, Boolean, null, array, or object. Datatypes for XML content can be included by using a DTD or XML schema to define an XML document's structure, but JavaScript datatypes are not a built-in feature of XML.

JSON can be parsed as JavaScript.—JSON represents JavaScript in a text format. Using JavaScript itself, you can convert JSON text to JavaScript.

For additional security, you can use a JSON parser for the conversion. Returning data as XML means that you need to parse the XML. This usually requires DOM methods and DOM manipulation. As you've seen in earlier chapters, this can become quite complex, even for simple data.

Page 27: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 27

<?xml version="1.0"?><classes>

<class><classID>CS115</classID><department>ComputerScience</department><credits req="yes">3</credits><instructor>Adams</instructor><title>Programming Concepts</title></class><class><classID semester="fall">CS205</classID><department>ComputerScience</department><credits req="yes">3</credits><instructor>Dykes</instructor><title>JavaScript</title></class><class><classID semester="fall">CS255</classID><department>ComputerScience</department><credits req="yes">3</credits><instructor>Brunner</instructor><title>Java</title></class>

</classes>

{"class1": [{"classID": "CS115","department": "Computer Science","credits": 3,"req": "yes","instructor" : "Adams","title" : "Programming Concepts"},{"classID": "CS205","semester": "fall","department": "Computer Science","credits": 3,"req": "yes","instructor" : "Dykes","title" : "JavaScript"},{"classID": "CS255","semester": "fall","department": "Computer Science","credits": 3,"req": "yes","instructor" : "Brunner",

"title" : "Java"}

]}

1. The name of the object has been changed from class toclass1becauseclassis a reserved word in JavaScript.

2.JSON isn't a document format, so it doesn't need structureslike elements, attributes, entities. Therefore, it can be smaller and more effiecient for transmission of large amountoOf data.

classes.txtclasses.xml

Page 28: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 28

Ajax & JSON

In the same way you create any Ajax request for text data, you can use the XMLHttpRequest object to create a request for JSON data.

If you're requesting JSON data directly from a JSON file on the server (in other words, not using a server-side language such as PHP as an intermediary to obtain the data), you can simply request the JSON file by name.request.open("GET", "classes.txt", true);

In this case, classes.txt is the name of the JSON data file, and request is the variable created to hold the XMLHttpRequestobject.

Page 29: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 29

Parsing the response

Once you receive the JSON data from the server, you can parse this response in two different ways. You can use JavaScript's built-in eval() function,

If you're making a request for JSON data, use the responseText property of the XMLHttpRequest object, then use eval() to convert the JSON text string into a JavaScript object.

var jsonResp = request.responseText; jsonResp = eval("(" + jsonResp + ")");

or, for extra security, you can use a JSON parser instead. In this case, you use responseText, but you use the parseJSON() method to convert the JSON text string into a JavaScript object.

var jsonResp = request.responseText; jsonResp = jsonResp.parseJSON();

In order to access the parseJSON() function, you also need to include a script tag referencing the json.js file.

<script type="text/javascript" src="json.js"></script>

Page 30: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 30

Adding JSON Data to your page

Once you've converted the JSON data to a JavaScript object, you can use JavaScript to extract the data from the object. For example, if the variable jsonResp contains a JavaScript array, you can use a for loop to iterate through the members of the array.

for (i=0; i < jsonResp.class1.length; i++) { ...

You won't need to use the DOM to extract the data from the response, but you're likely to use DOM methods such as createElement() to dynamically add the response data to your page.

See example on page 360 of your Ajax Textbook

Page 31: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 31

JSON Summary

JSON is a text format that uses two structures for data transmission:1. JavaScript object literals containing name-value pairs 2. JavaScript array literals containing values.

Unlike XML, JSON is designed only for data transmission, not as a document format.

Douglas Crockford's JSON parser is a JavaScript file (json.js) that can be used to add methods to JavaScript to convert between JSON data and JavaScript objects.

The responseText property can be used to return a string of JSON data from an Ajax request.

JSON data can be parsed by converting the string to a JavaScript object using eval() or parseJSON()

Page 32: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 32

Connection to DBMS

Example: MySQL

Page 33: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 33

Web Applications & DBMS

A useful Ajax application includes server side scripting (e.g. PHP) and connection to a relational DBMS (e.g. MySQL).Use your knowledge from database class (CSci4707 & CSci 5707) to use SQL to create a database, create tables, and CRUD operations on tables.You can use almost any DBMS with a web application, depending on your experience with database design, your projected number of site visitors, and your budget.

Page 34: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 34

Quick SQL with MySQL

CREATE DATABASE tasks; USE tasks; CREATE TABLE tasks ( task_id int not null auto_increment, task varchar(100) not null, rank int, primary key (task_id) ); INSERT INTO tasks (task) VALUES ("New forecast dates for Med3 Project"); INSERT INTO tasks (task) VALUES ("Call Joe Smith and schedule meeting"); INSERT INTO tasks (task) VALUES ("Get estimates from Laura");

SELECT * FROM tasks;

Page 35: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 35

Creating s DB connection

To interact with the MySQL database from the application, you must create a connection to the database. You can save all the connection details in one PHP file, then use that file as an external file that can be called from other PHP files using the require_once function.

You must supply four pieces of information to make a database connection from your application:

Host nameUsernamePasswordDatabase name

Once values are set for the host, user, and password, you can make a connection to MySQL using the mysql_connect function.

Page 36: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 36

Connection to MySQL

<?phpdefine ("MYSQLHOST", "localhost");define ("MYSQLUSER", "root");define ("MYSQLPASS", "****");define ("MYSQLDB", "tasks");function dbConnect() {$db = mysql_connect(MYSQLHOST, MYSQLUSER, MYSQLPASS);if (!$db) {

return false;}

else {mysql_select_db (MYSQLDB, $db);}

return $db;}?>

Change these values to those that work with your MySQL database. Once the connection is created, the mysql_select_db function tells MySQL the name of the database (tasks) to use for queries.

define in PHP: http://us2.php.net/define

Page 37: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 37

Creating DB Queries<?php

function getTasks(){ $query = 'SELECT task_id, task FROM tasks ORDER BY

rank';$result = mysql_query($query);$tasks = array();while ($row = mysql_fetch_object($result)) {

$tasks[$row->task_id] = $row->task;}

return $tasks;}

The getTasks function is used by the application to query the database and supply the information to dynamically display the current database values in a list. It will be used to create the list values when the index pageof the application (index.php) is loaded in a browser. It's also used by thesecond function on the tasks.php page, the taskOrder function.

The mysql_fetch_object function returns a row as an object.

Page 38: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 38

The taskOrder function is invoked to create a database query whenever the list order is changed. An Ajax request on the index page uses the POST method to call the order.php file. This file calls the taskOrder function. By calling the order.php file via an Ajax request, JavaScript is used to invoke a PHP function.

function taskOrder($key){

if (!isset($_POST[$key]))return;

$tasks = getTasks();$queries = array();$rank = 1;foreach ($_POST[$key] as $task_id) {

if (!array_key_exists($task_id, $tasks))continue;

$query = sprintf('UPDATE tasks SET rank = %d WHERE task_id =$rank,$task_id);

mysql_query($query);$rank++;

}}

?> For INSERT and DELETE see page 374

Page 39: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 39

What we learned today

Ajax Framework & LibrariesJSONConnection to DBMS

Page 40: CSci 4131: Internet Programming Class 10: April 15, 2008

Jamshid A. Vayghan, Ph.D. 40

Next Class (April 22, 2008)Topics to cover:

FeedsMashup

Readings:Ajax book (Chapters 7,10)

Homework Due:Assignment 7 (Due May 2)