introduction to web 2-0

44
Introduction to Web 2.0 Introduction to Web 2.0 Programming Programming Using JavaScipt, CSS, and jQuery Using JavaScipt, CSS, and jQuery By John Valance JValance Consulting Email: [email protected] Vermont Midrange Users Group Conference – Sept. 28, 2010

Upload: others

Post on 12-Sep-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Web 2-0

Introduction to Web 2.0 Introduction to Web 2.0

ProgrammingProgramming

Using JavaScipt, CSS, and jQueryUsing JavaScipt, CSS, and jQuery

By John Valance

JValance Consulting

Email: [email protected]

Vermont Midrange Users Group Conference – Sept. 28, 2010

Page 2: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 2

About John Valance About John Valance

Independent consultant Independent consultant –– Specialty is helping iSeries shops develop web Specialty is helping iSeries shops develop web

applicationsapplications

–– Training, mentoring, consultation and codingTraining, mentoring, consultation and coding

Over 20 years iSeries/AS400 experienceOver 20 years iSeries/AS400 experience

Ten years of web development experienceTen years of web development experience

Frequent presenter on web development topicsFrequent presenter on web development topics

Web scripting language of choice = PHPWeb scripting language of choice = PHP–– Also experienced with SQL, Java, RPGLEAlso experienced with SQL, Java, RPGLE

Trainer for Zend TechnologiesTrainer for Zend Technologies–– Teaches Intro to PHP for RPG programmers Teaches Intro to PHP for RPG programmers

Page 3: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 3

What We Will CoverWhat We Will Cover

Web 2.0 application characteristicsWeb 2.0 application characteristics

Some background Some background –– Legacy web appsLegacy web apps

CSS CSS

JavaScriptJavaScript

DOM DOM –– Legacy and W3CLegacy and W3C

jQuery frameworkjQuery framework

Ajax with jQueryAjax with jQuery

Web 2.0 application demoWeb 2.0 application demo

Corvette America dealer order entry demoCorvette America dealer order entry demo

Page 4: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 4

What Do We Mean By Web 2.0?What Do We Mean By Web 2.0?

Hard to Define Hard to Define

Includes a broad array of paradigms for Includes a broad array of paradigms for interacting through the web, including:interacting through the web, including:–– social networkingsocial networking

–– multimulti--mediamedia–– web servicesweb services

–– mobile devices mobile devices

We will focus on the enabling technologies used We will focus on the enabling technologies used in browserin browser--based applicationsbased applications–– Introduce the concepts and techniquesIntroduce the concepts and techniques

–– Native browser technologies onlyNative browser technologies onlyNot Flash or other plugNot Flash or other plug--in related techniquesin related techniques

Page 5: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 5

Characteristics of Web 2.0 ApplicationsCharacteristics of Web 2.0 Applications

Highly Interactive / High performance Highly Interactive / High performance –– Response time and functionality rival PC Response time and functionality rival PC

desktop applicationsdesktop applications

Very dynamic interfaceVery dynamic interface–– expand/collapseexpand/collapse

–– drag/dropdrag/drop

–– intellisenseintellisense

UI is controlled by Javascript and CSSUI is controlled by Javascript and CSS–– Lots of clientLots of client--side codeside code

Page 6: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 6

Characteristics of Web 2.0 ApplicationsCharacteristics of Web 2.0 Applications

Interaction with Server via Ajax Interaction with Server via Ajax –– Used to retrieve bits of data from the server without Used to retrieve bits of data from the server without

reloading the entire pagereloading the entire page

–– Can also update the server through Ajax callsCan also update the server through Ajax calls

Use of Javascript frameworks to simplify clientUse of Javascript frameworks to simplify client--side code and crossside code and cross--browser issuesbrowser issues–– jQueryjQuery

–– PrototypePrototype

–– DojoDojo

–– ExtJSExtJS

–– script.aculo.usscript.aculo.us

Page 7: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 7

Background:Background:

HTTP and Static Web ContentHTTP and Static Web Content

HTTP = Request / Response protocolHTTP = Request / Response protocol

–– Client (browser) Client (browser) requestsrequests a file from servera file from server

–– Server Server respondsresponds with the file requestedwith the file requested

Content is StaticContent is Static

–– HTML documents and other files are returned HTML documents and other files are returned ““asas--isis””

–– No preNo pre--processing step prior to responseprocessing step prior to response

Updates to content are done offline by HTML Updates to content are done offline by HTML

codercoder

–– HTML is hardHTML is hard--codedcoded

Page 8: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 8

Legacy Web (1.0) ApplicationLegacy Web (1.0) ApplicationWe can create database applications We can create database applications

using a simple HTML frontusing a simple HTML front--endend

Still uses HTTP request/response protocolStill uses HTTP request/response protocol

Can deliver dynamic content via serverCan deliver dynamic content via server--side scripts side scripts –– e.g.: PHP, JSP, CGI, etc.e.g.: PHP, JSP, CGI, etc.

Dynamic content typically retrieved from a databaseDynamic content typically retrieved from a database

Database content can also be updated via HTML form Database content can also be updated via HTML form inputsinputs

Interactions with server typically involve a form Interactions with server typically involve a form submission as the request, with a complete HTML submission as the request, with a complete HTML document returned as the response document returned as the response

Page 9: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 9

Some Aspects of Some Aspects of

Web 1.0 ApplicationsWeb 1.0 Applications

Limited functionalityLimited functionality

Limited types of inputs and UI controlsLimited types of inputs and UI controls

Slow response (due to large payload of Slow response (due to large payload of HTML documents + ancillary files)HTML documents + ancillary files)

Page reloads may reposition at top of Page reloads may reposition at top of pagepage

ButBut……

You You can can create useful applications with create useful applications with simple HTML forms + server scripts.simple HTML forms + server scripts.

Page 10: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 10

Languages Involved in a Languages Involved in a

Typical Web ApplicationTypical Web Application

Client Side:Client Side:–– HTMLHTML

–– CSSCSS

–– JavaScriptJavaScript

Server Side:Server Side:–– SQLSQL

–– <<your favorite server scripting languageyour favorite server scripting language>:>:PHPPHPJavaJava

RPGRPG

PHP calling RPGPHP calling RPG

Page 11: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 11

Legacy Web Application DemoLegacy Web Application Demo

Customer Inquiry ApplicationCustomer Inquiry Application

–– Uses HTML form submission on clientUses HTML form submission on client

–– Uses PHP and mySql on serverUses PHP and mySql on server

““SelfSelf--submittingsubmitting”” form scriptform script

–– Calls itselfCalls itself

If customer number present on request, it will If customer number present on request, it will

retrieve database inforetrieve database info

Else it will just present input formElse it will just present input form

Page 12: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 12

Modern Web 2.0 Modern Web 2.0

Application ArchitectureApplication ArchitectureHeavy reliance on JavaScript and CSSHeavy reliance on JavaScript and CSS

CSS determines visual aspects of HTML CSS determines visual aspects of HTML elementselements–– Colors, fonts, visibility, positioning, bordersColors, fonts, visibility, positioning, borders……

JavaScript is used to:JavaScript is used to:–– React to events (mouse movements and clicks, React to events (mouse movements and clicks,

keystrokes, page loadkeystrokes, page load……))

–– Modify CSS and other attributes of HTML elementsModify CSS and other attributes of HTML elements

–– Add and remove HTML elements or change text Add and remove HTML elements or change text contentscontents

–– Call scripts on server via AjaxCall scripts on server via Ajaxretrieve or update database informationretrieve or update database information

Page 13: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 13

What is CSS?What is CSS?

CSS stands for Cascading Style SheetsCSS stands for Cascading Style Sheets

Styles define how to display HTML elementsStyles define how to display HTML elements

–– Styles were added to HTML 4.0 to help separate Styles were added to HTML 4.0 to help separate

content from presentation. content from presentation.

Styles are normally stored in Style SheetsStyles are normally stored in Style Sheets

–– a list of presentation attributes that together define the a list of presentation attributes that together define the

style of a page or an entire site.style of a page or an entire site.

External Style Sheets are stored in .css filesExternal Style Sheets are stored in .css files

–– External Style Sheets can save you a lot of work, External Style Sheets can save you a lot of work,

since sitesince site--wide style changes can be made in one file.wide style changes can be made in one file.

Page 14: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 14

CSS SyntaxCSS Syntaxselector {

property: value;

property: value;

...

}

SelectorSelector: identifies a part of the document to be styled: identifies a part of the document to be styled–– HTML tag name, Class name, or a Unique ID (more on this HTML tag name, Class name, or a Unique ID (more on this

comingcoming……))

PropertyProperty: A specific presentation attribute to be styled : A specific presentation attribute to be styled – color, font-weight, border attributes, visibility

ValueValue: How the presentation attribute should be styled : How the presentation attribute should be styled color: red; font-weight: bold; border: 2px solid blue;

Page 15: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 15

Where can Styles be specified?Where can Styles be specified?

Inside a single HTML element<table style=“border:none; color:blue”>

Inside the <head> element of an HTML page<head>

<style type=“text/css”>

table { border:none; color:blue }

</style>

</head>

In an external CSS file<head>

<link rel="stylesheet" type="text/css”

href=“siteStyle.css" />

</head>

Page 16: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 16

Examples of CSS SelectorsExamples of CSS SelectorsHTML Tag Name:BODY { font: arial; font-size: 12pt;

color: navy }

– Can use any HTML tag name– Applies to all occurences of the tag throughout a document

Class Name - precede with period (.) :.error { color: red; font-weight: bold}

<p class=“error”>Invalid email address</p>

– Can specify the same class on many different HTML tags

Unique ID – precede with hash (#):#shipto { visibility: hidden }

<div id=“shipto”> <table>... </div>

– ID name should only occur once in HTML document

Page 17: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 17

Demo of CSS StylesheetDemo of CSS Stylesheet

sitestyle.css, used in customer inquiry sitestyle.css, used in customer inquiry

demodemo

Page 18: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 18

What is JavaScript?What is JavaScript?

It isnIt isn’’t Java, but similar syntax t Java, but similar syntax

–– C type syntaxC type syntax

Scripting language for web browsers Scripting language for web browsers

–– Runs on the clientRuns on the client--side onlyside only

–– All browsers have builtAll browsers have built--in JavaScript in JavaScript interpreter interpreter –– you donyou don’’t buy it or install it.t buy it or install it.

Interpreted at runInterpreted at run--time (as page loads)time (as page loads)

Page 19: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 19

What Can JavaScript Do?What Can JavaScript Do?

Manipulate the HTML document after it has been sent to Manipulate the HTML document after it has been sent to the browser in a myriad of waysthe browser in a myriad of waysHandle events Handle events –– mouse clicks, cursor movement, etc.mouse clicks, cursor movement, etc.

Communicate with user via popCommunicate with user via pop--up alerts.up alerts.

Handle forms and input valuesHandle forms and input values

Alter CSS attributes of HTML elements Alter CSS attributes of HTML elements Add, change, delete HTML elementsAdd, change, delete HTML elements

Open & close windows, and communicate between Open & close windows, and communicate between windowswindows

Read and write cookiesRead and write cookies

Ajax Ajax –– call server scripts without page reloadcall server scripts without page reload

Page 20: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 20

JavaScript Event HandlingJavaScript Event Handling

JavaScript can be used to react to events in the browserJavaScript can be used to react to events in the browser–– mouse clicks, mouse movement, keystrokes, movement in and mouse clicks, mouse movement, keystrokes, movement in and

out of form fields, etc.out of form fields, etc.–– One of JavaScriptOne of JavaScript’’s most useful capabilities with regards to Web s most useful capabilities with regards to Web

2.02.0

Can code Can code ““event handlersevent handlers”” as attributes of HTML tagsas attributes of HTML tags

Event handlers start with Event handlers start with ““onon…”…”–– Onclick, onfocus, onblur, onmouseover, onmouseoutOnclick, onfocus, onblur, onmouseover, onmouseout

Event handler attributes specify some javascript code to Event handler attributes specify some javascript code to execute as their valueexecute as their value–– Can be individual statements or function callCan be individual statements or function call<body onload=“setInputDefaults();”>

<input name=“company”onblur=“this.value=this.value.touppercase();”>

<tr onmouseover=“this.className=‘hilite’;”>

Page 21: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 21

JavaScript DemoJavaScript Demo

Simple form validation scriptSimple form validation script

Some dynamic HTML examplesSome dynamic HTML examples

Page 22: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 22

Document Object ModelDocument Object Model

DOM is how JavaScript interacts with HTML document DOM is how JavaScript interacts with HTML document elementselementsHTML document is a heirarchy of elements defined by HTML document is a heirarchy of elements defined by tagstags

As browser loads document, these elements are loaded As browser loads document, these elements are loaded into objects that JavaScript can easily accessinto objects that JavaScript can easily access

JavaScript uses dot (.) notation to access objects and JavaScript uses dot (.) notation to access objects and their properties:their properties:

document.searchForm.searchField.value = ‘Enter keyword’;

Object properties can be read or modified by JavaScriptObject properties can be read or modified by JavaScript–– Some properties are readSome properties are read--onlyonly

Page 23: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 23

DOM Object PropertiesDOM Object Properties

Each DOM object can have properties:Each DOM object can have properties:

–– Tag attributes: Tag attributes:

<img src=“companylogo.gif”>

<h1 style=“color: blue; font-size: 14pt”>

–– Tag contents:Tag contents:<p>This is a short paragraph.</p>

–– Nested HTML tags (= nested JS objects):Nested HTML tags (= nested JS objects):<document>

<form name=“orderForm”>

<input name=“zipCode”>

document.orderForm.zipCode

Page 24: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 24

Navigating the DOMNavigating the DOM

Legacy DOM (DOM Level 0, preLegacy DOM (DOM Level 0, pre--IE4)IE4)

Limited object modelLimited object model

documentdocument object has properties that are arrays of specific HTML object has properties that are arrays of specific HTML collectionscollections– anchors[], applets[], forms[], images[], links[]

forms[] object is the most important of these.

– Each forms[] object also contains a collection of elements[], which are the form’s input elements

These arrays can be iterated over using a loop and an incrementeThese arrays can be iterated over using a loop and an incremented d index variable.index variable.

Properties can by read and changed, but DOM level 0 does not Properties can by read and changed, but DOM level 0 does not allow altering document text content or reallow altering document text content or re--flowing the document.flowing the document.

Example: Example:

– document.forms[0].elements[3].value = ‘123.45’;

Page 25: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 25

Naming DOM ElementsNaming DOM ElementsIt is easier to navigate the DOM by naming elementsIt is easier to navigate the DOM by naming elements

<form name=“myForm”>

<input type=“text” name=“UserName”>

</form>

<script type=“text/javascript”>

document.myForm.UserName = ‘JOHNV’;

</script>

Can also us id attribute to get a specific elementCan also us id attribute to get a specific element

<input type=“text” id=“UserName”>

<script type=“text/javascript”>

var userName = document.getElementById( ‘UserName’);

userName.value = ‘JOHNV’;

</script>

Page 26: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 26

W3C DOMW3C DOMImplements a fully accessible and modifiable tree structure objeImplements a fully accessible and modifiable tree structure object ct modelmodel

<html>

<head>

<title>This is a Document!</title>

</head>

<body>

<h1>This is a header!</h1>

<p id="excitingText">

This is a paragraph! <em>This is emphasized</em>!

</p>

<p>

This is also a paragraph, but it's not nearly as exciting

as the last one.

</p>

</body>

</html>

From: Traversing the DOM by Mike West - http://dev.opera.com/articles/view/traversing-the-dom/

Page 27: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 27

W3C DOM Tree W3C DOM Tree

From: Traversing the DOM by Mike West - http://dev.opera.com/articles/view/traversing-the-dom/

Page 28: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 28

Navigating W3C DOMNavigating W3C DOM

W3C DOM is implemented as a tree of various W3C DOM is implemented as a tree of various types of Node objectstypes of Node objects

Each Node object defines properties and Each Node object defines properties and methods for traversing and manipulating the methods for traversing and manipulating the tree. tree.

–– PropertiesProperties

childNodes childNodes -- a list of children of the nodea list of children of the node

firstChild, lastChild, nextSibling, previousSibling, parentNodefirstChild, lastChild, nextSibling, previousSibling, parentNode

–– MethodsMethods

appendChild( ), removeChild( ), replaceChild( ), appendChild( ), removeChild( ), replaceChild( ), insertBefore( )insertBefore( )

Page 29: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 29

Types of NodesTypes of Nodes

Every Node object has a nodeType property Every Node object has a nodeType property

that specifies what kind of node it is.that specifies what kind of node it is.

Node.ELEMENT_NODENode.ELEMENT_NODEElement Element

Node.TEXT_NODENode.TEXT_NODEText Text

Node.DOCUMENT_NODENode.DOCUMENT_NODEDocumentDocument

Node.COMMENT_NODENode.COMMENT_NODECommentComment

Node.ATTRIBUTE_NODENode.ATTRIBUTE_NODEAttr Attr

nodeType constant nodeType constant nodeTypenodeType

Page 30: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 30

Getting a Specific NodeGetting a Specific Node

You could start at the document root, and work down to You could start at the document root, and work down to the desired elementthe desired element–– Very cumbersomeVery cumbersome–– Impossible if elements are added/deleted dynamicallyImpossible if elements are added/deleted dynamically

Best way is to assign an ID attributeBest way is to assign an ID attribute–– Use document.getElementById(Use document.getElementById(‘‘myTagIdmyTagId’’))

Can also get all elements by tag nameCan also get all elements by tag name–– document.getElementsByTagName(document.getElementsByTagName(‘‘inputinput’’))

Returns an array of all input elements in the documentReturns an array of all input elements in the document

–– Can start at a specific node within document treeCan start at a specific node within document treevar itemsTable = document.getElementById("items");

var rows = itemsTable.getElementsByTagName("tr");

var numItems = rows.length;

Page 31: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 31

Traversing the DOM examplesTraversing the DOM examples

Starting at document root, without IDsStarting at document root, without IDsvar theHtmlNode = document.childNodes[0];

var theBodyNode = theHtmlNode.childNodes[1];

var theParagraphNode = theBodyNode.childNodes[1];

alert( "theParagraphNode is a " +

theParagraphNode.nodeName + " node!" );

Starting at a specific node, retrieved by IDStarting at a specific node, retrieved by IDvar paragraphNode =

document.getElementById('excitingText');

alert( “The exciting text is " +

paragraphNode.innerHTML );

}

Page 32: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 32

Problems with Basic JavaScriptProblems with Basic JavaScript

CrossCross--browser compatability issuesbrowser compatability issues

Awkwardness and Complexity of CodeAwkwardness and Complexity of Code

–– Abstract DOM traversal and selectionAbstract DOM traversal and selection

Arrays, Loops, IndexesArrays, Loops, Indexes

Referencing Nodes and ElementsReferencing Nodes and Elements

Testing types and attributes of nodesTesting types and attributes of nodes

PerformancePerformance

Page 33: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 33

jQuery to the RescuejQuery to the Rescue

Most widely used JavaScript frameworkMost widely used JavaScript frameworkGreatly simplifies coding of browser scriptingGreatly simplifies coding of browser scripting–– DOM selection and traversalDOM selection and traversal–– Dynamic UI controls Dynamic UI controls –– Ajax callsAjax calls

Seemless integration with CSSSeemless integration with CSS–– Easy to select elements via JavaScript (why itEasy to select elements via JavaScript (why it’’s called jQuery)s called jQuery)–– Easy to modify HTML attributes and CSS propertiesEasy to modify HTML attributes and CSS properties

Intuitive syntax (wellIntuitive syntax (well…… somewhat)somewhat)Open source and free (download from jQuery.org)Open source and free (download from jQuery.org)

High performance and small file size (~72K)High performance and small file size (~72K)No plugNo plug--ins requiredins required–– Built on pure JavaScriptBuilt on pure JavaScript

Page 34: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 34

Example: Toggle VisibilityExample: Toggle Visibility

Basic JavaScriptBasic JavaScriptfunction toggleBox () {

var elem = document.getElementById('box');

if (elem.style.visibility == "hidden") {

elem.style.visibility = "visible";

} else {

elem.style.visibility = "hidden;

}

}

Using jQueryUsing jQuery

$("#box").toggle();

Page 35: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 35

jQuery SyntaxjQuery Syntax

$(“<selector>").<method>();

$( )

–– This calls jQueryThis calls jQuery

–– Synonymous with calling Synonymous with calling jQuery( )–– This example could be coded This example could be coded jQuery("#box").toggle();

$("#box")

– This selects the element with id=“box”

$("#box").toggle()

– This toggles the visibility (hidden/visible) of the box elementSame as if statement in previous slide

Could also use show(), hide(), slideDown(), slideUp(), slideToggle(), fadeIn(), fadeOut()

Page 36: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 36

SelectorsSelectors

jQuery selectors = CSS selectorsjQuery selectors = CSS selectors–– HTML tag nameHTML tag name

$($(‘‘inputinput’’)) –– selects all selects all <input><input> elementselements

$($(‘‘pp’’)) –– selects all selects all <p><p> elementselements

–– Class attributeClass attribute$($(‘‘.inputLabel.inputLabel’’)) –– selects any element with selects any element with class=class=““inputLabelinputLabel””

–– ID attributeID attribute$($(‘‘#mainContent#mainContent’’)) –– selects the element with selects the element with id=id=““mainContentmainContent””

Page 37: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 37

Combined SelectorsCombined Selectors

$($(‘‘p.helpTextp.helpText’’))

–– Select all paragraphs with class=Select all paragraphs with class=““helpTexthelpText””

–– No space between tag and classNo space between tag and class

$($(‘‘div#shippingInfo .labeldiv#shippingInfo .label’’))

–– Select all elements with class=Select all elements with class=““labellabel””, but only within , but only within the <div> tag with id=the <div> tag with id=““shippingInfoshippingInfo””

–– Note the space between the two selectors, indicates Note the space between the two selectors, indicates descendent relationshipdescendent relationship

$($(‘‘h1, h2, h3h1, h2, h3’’))

–– Select all <h1>, <h2>, and <h3> tagsSelect all <h1>, <h2>, and <h3> tags

–– Commas means a list of selectorsCommas means a list of selectors

Page 38: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 38

MethodsMethodsOnce elements are selected, we can call a variety of methods to Once elements are selected, we can call a variety of methods to alter alter

the documentthe document

hide(), show()hide(), show() and related methods and related methods –– Saw these earlierSaw these earlier

addClass(), removeClass()addClass(), removeClass()

–– Add and remove a CSS classAdd and remove a CSS class

css()css()

–– Directly alter values of CSS propertiesDirectly alter values of CSS properties

attr(), removeAttr()attr(), removeAttr()

–– Change or remove HTML tag attributesChange or remove HTML tag attributes

text()text()

–– Change text contained between open/close tagsChange text contained between open/close tags

insertBefore(), insertAfter, prepend() insertBefore(), insertAfter, prepend() append(), remove(), replaceWith(), clone()append(), remove(), replaceWith(), clone()

–– Allows insertion, deletion, moving, copying of HTML elementsAllows insertion, deletion, moving, copying of HTML elements

Page 39: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 39

Ajax Ajax Stands for Asynchronous JavaScript and XMLStands for Asynchronous JavaScript and XMLAllows calling a server script from within an HTML page Allows calling a server script from within an HTML page via JavaScriptvia JavaScript–– Server script can be any language (PHP, Java, RPG)Server script can be any language (PHP, Java, RPG)–– Call is Call is asynchronousasynchronous (JavaScript doesn(JavaScript doesn’’t wait for response)t wait for response)

Can specify a JavaScript function to be called when response is Can specify a JavaScript function to be called when response is receivedreceived

No page reloadNo page reloadCan retrieve and update data on server very quicklyCan retrieve and update data on server very quickly–– SubSub--second response is typical (like a local PC application)second response is typical (like a local PC application)–– Can modify page contents or styling based on whatCan modify page contents or styling based on what’’s returned by s returned by

the server scriptthe server scriptUse jQuery selectors and methods to update page contentUse jQuery selectors and methods to update page content

Ajax calls are simplified by using jQueryAjax calls are simplified by using jQuery–– Eliminates crossEliminates cross--browser syntactical differencesbrowser syntactical differences

Page 40: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 40

Making an Ajax CallMaking an Ajax Call

$.get(<url>, <function$.get(<url>, <function--name>);name>);function clickButton() {

var url = 'getCustomer.php?custNum=1234';

$.get(url, processResponse);

}

function processResponse( data ) {

alert('data returned = ' + data);

}

Can also use $.post(<url>, <functionCan also use $.post(<url>, <function--name>);name>);–– Depends on what the server script expects and how Depends on what the server script expects and how

much data is being passedmuch data is being passed

Data returned by server script can be any formatData returned by server script can be any format–– XML, HTML, JSONXML, HTML, JSON

Page 41: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 41

JSONJSONJSON = JavaScript Object NotationJSON = JavaScript Object Notation

Simpler, more compact format than XMLSimpler, more compact format than XML–– Basically a list of name:value pairs enclosed in bracesBasically a list of name:value pairs enclosed in braces{"error":true, "message":"Invalid zip code"}

Easy to use and parseEasy to use and parse

PHP has json_encode() function PHP has json_encode() function –– Transform variables into JSON as Transform variables into JSON as

{<var{<var--name>:<varname>:<var--value>}value>}

–– Can be used with arrays, including nested arraysCan be used with arrays, including nested arrays

JavaScript can easily parse JSON into variablesJavaScript can easily parse JSON into variables–– Can use jQuery functions or standCan use jQuery functions or stand--alone parsersalone parsers

Page 42: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 42

Demo Corvette AmericaDemo Corvette America

Auto parts & accessories distributor in PAAuto parts & accessories distributor in PA

Created order entry application for their wholesale Created order entry application for their wholesale customers (dealers)customers (dealers)

22--man RPG shop with no prior web development man RPG shop with no prior web development experienceexperience–– Team also included a graphic designer from marketing Team also included a graphic designer from marketing

departmentdepartment

Wanted to create the application inWanted to create the application in--house, using PHP house, using PHP hosted on iSeries (Zend Core)hosted on iSeries (Zend Core)

Features Features –– Sophisticated item searchSophisticated item search

–– Multiple shopping baskets per customerMultiple shopping baskets per customer

–– Ajax calls for item validation and adding items to baskets Ajax calls for item validation and adding items to baskets

Page 43: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 43

SummarySummaryWeb 2.0 is the current standard for web application Web 2.0 is the current standard for web application developmentdevelopment

Provides rich UI and high performanceProvides rich UI and high performance–– On par with desktop applicationsOn par with desktop applications

Capabilities based on JavaScript and CSS, applied Capabilities based on JavaScript and CSS, applied dynamically to HTML documentsdynamically to HTML documents

More clientMore client--side codingside coding

Ajax technology allows JavaScript to communicate Ajax technology allows JavaScript to communicate directly with serverdirectly with server–– Data retrieved can be inserted into HTML dynamicallyData retrieved can be inserted into HTML dynamically

jQuery (and other JS frameworks) can greatly simplify jQuery (and other JS frameworks) can greatly simplify and standardize coding of Web 2.0 applicationsand standardize coding of Web 2.0 applications

Page 44: Introduction to Web 2-0

Sept. 28, 2010 – VTMUG Conference. Introduction to Web 2.0 – John Valance (Copyright 2010) 44

InquiriesInquiries

Please contact John Valance at:Please contact John Valance at:

[email protected]@sprynet.com

802802--355355--40244024

Happy coding!Happy coding!