• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
CSci 4131: Internet Programming Class 10: April 15, 2008

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






Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Adobe PDF

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.

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

    CSci 4131: Internet Programming Class 10: April 15, 2008 CSci 4131: Internet Programming Class 10: April 15, 2008 Presentation Transcript

    • CSci 4131: Internet Programming Class 10: April 15, 2008 Jamshid A. Vayghan, Ph.D. Spring 2008 Jamshid A. Vayghan, Ph.D. 1
    • Today’s Agenda Ajax Frameworks & Libraries (Appendix B) JSON (Chapter 11) Connection to DBMS (Chapter 12) Jamshid A. Vayghan, Ph.D. 2
    • 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. Jamshid A. Vayghan, Ph.D. 3
    • Client side Jamshid A. Vayghan, Ph.D. 4
    • 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> Jamshid A. Vayghan, Ph.D. 5
    • 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); Jamshid A. Vayghan, Ph.D. 6
    • 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_ Framework Download prototype.js from http://prototypejs.org/ Jamshid A. Vayghan, Ph.D. 7
    • 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 paragraphs with the class name red: var myPara = $$("p.red"); Jamshid A. Vayghan, Ph.D. 8
    • 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> Jamshid A. Vayghan, Ph.D. 9
    • Dojo Dojo 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> Jamshid A. Vayghan, Ph.D. 10
    • 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> Jamshid A. Vayghan, Ph.D. 11
    • MochiKit MochiKit calls itself a "lightweight JavaScript library." It's available as a free-standing download at http://www.mochikit.com and 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, sortable objects, 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. Jamshid A. Vayghan, Ph.D. 12
    • Server Side Jamshid A. Vayghan, Ph.D. 13
    • 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 Basecamp software for project management online. Rails provides Ajax support through the Prototype library, which is 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(). Jamshid A. Vayghan, Ph.D. 14
    • 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 type An XmlHttpExecutor component JavaScript Web service proxies Jamshid A. Vayghan, Ph.D. 15
    • JavaScript Object Notation: JSON Jamshid A. Vayghan, Ph.D. 16
    • 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 Jamshid A. Vayghan, Ph.D. 17
    • 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? Jamshid A. Vayghan, Ph.D. 18
    • 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. Jamshid A. Vayghan, Ph.D. 19
    • JSON Syntax JSON consists of two data structures: Objects—An unordered collection of name/value pairs Arrays—An ordered collection of values There are no variables or other control structures in JSON. It's designed 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; Jamshid A. Vayghan, Ph.D. 20
    • JSON Data Types JSON data structures can include any of the following types of data: String Number Boolean value (true/false) null Object Array 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"" Jamshid A. Vayghan, Ph.D. 21
    • 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 } Jamshid A. Vayghan, Ph.D. 22
    • 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"] Jamshid A. Vayghan, Ph.D. 23
    • 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() Jamshid A. Vayghan, Ph.D. 24
    • toJSONString() method The 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> Jamshid A. Vayghan, Ph.D. 25
    • Data Transmission Formats Either 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. Jamshid A. Vayghan, Ph.D. 26
    • <?xml version="1.0"?> classes.xml {"class1": [ classes.txt <classes> { <class> "classID": "CS115", <classID>CS115</classID> "department": "Computer Science", <department>ComputerScience</department> "credits": 3, <credits req="yes">3</credits> "req": "yes", <instructor>Adams</instructor> "instructor" : "Adams", <title>Programming Concepts</title> "title" : "Programming Concepts" </class> }, <class> { <classID semester="fall">CS205</classID> "classID": "CS205", <department>ComputerScience</department> <credits req="yes">3</credits> "semester": "fall", <instructor>Dykes</instructor> "department": "Computer Science", <title>JavaScript</title> "credits": 3, </class> "req": "yes", <class> "instructor" : "Dykes", <classID semester="fall">CS255</classID> "title" : "JavaScript" <department>ComputerScience</department> }, <credits req="yes">3</credits> { <instructor>Brunner</instructor> "classID": "CS255", <title>Java</title> "semester": "fall", </class> "department": "Computer Science", </classes> "credits": 3, 1. The name of the object has been changed from class to "req": "yes", class1becauseclassis a reserved word in JavaScript. "instructor" : "Brunner", 2.JSON isn't a document format, so it doesn't need structures "title" : "Java" like elements, attributes, entities. Therefore, it can be } smaller and more effiecient for transmission of large amount ] oOf data. } Jamshid A. Vayghan, Ph.D. 27
    • 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 XMLHttpRequest object. Jamshid A. Vayghan, Ph.D. 28
    • 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> Jamshid A. Vayghan, Ph.D. 29
    • 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 Jamshid A. Vayghan, Ph.D. 30
    • 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() Jamshid A. Vayghan, Ph.D. 31
    • Connection to DBMS Example: MySQL Jamshid A. Vayghan, Ph.D. 32
    • 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 (CSci 4707 & 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. Jamshid A. Vayghan, Ph.D. 33
    • 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; Jamshid A. Vayghan, Ph.D. 34
    • 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 name Username Password Database name Once values are set for the host, user, and password, you can make a connection to MySQL using the mysql_connect function. Jamshid A. Vayghan, Ph.D. 35
    • Connection to MySQL define in PHP: http://us2.php.net/define <?php define ("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. Jamshid A. Vayghan, Ph.D. 36
    • 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; } The mysql_fetch_object function returns a row as an object. 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 page of the application (index.php) is loaded in a browser. It's also used by the second function on the tasks.php page, the taskOrder function. Jamshid A. Vayghan, Ph.D. 37
    • 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 Jamshid A. Vayghan, Ph.D. 38
    • What we learned today Ajax Framework & Libraries JSON Connection to DBMS Jamshid A. Vayghan, Ph.D. 39
    • Next Class (April 22, 2008) Topics to cover: Feeds Mashup Readings: Ajax book (Chapters 7,10) Homework Due: Assignment 7 (Due May 2) Jamshid A. Vayghan, Ph.D. 40