Você está na página 1de 254

JQUERY WORKSHOP

Zubin K ,SCJP, MCSD,PMP,PGDBA, ITILv3

TRAINING EXPECTATIONS

Name Experience in Jquery Expectations from Training

Use slides to present key points Case Study based approach Practical -60-% Theory 30% Encourage discussions and questions Have flexible flow to address the needs

Introduction to Java Script DOM and Objects Overview JQuery introduction Basic Jquery functions Selectors Util functions

Introduction to AJAX AJAX with Jquery using XML Jquery Animation JQGrid Forms Plugin

JavaScript access to the elements of an HTML document. An object hierarchy Provides access to elements via:
ID (ID attribute of HTML tags) Order of elements in document Order of element in collection of similar elements.

this will be the ID we use to locate the object that represents this paragraph

<P ID=bestparagraph>This is the best paragraph in the document!</P> <SCRIPT> b = document.getElementById("bestparagraph"); b.innerHTML="Hi world!"; </SCRIPT> <P>Told you so</P> innerHTML is an attribute of an object that corresponds to an HTML tag. Its value is the stuff between the start tag and the end tag.

dom1.html

If you assign an ID attribute to all your HTML tags, you can access the objects that correspond to those elements directly. The JavaScript document object supports a method that allows you to get at the object that represents an HTML tag with a specific ID.
document.getElementById(foo);

You must use unique names!

Generally you should not have JavaScript variables with the same name as an ID you use to identify an HTML element.
Some browsers automatically create an variable with the same name as an ID attribute. Some browsers don't.

10

DOM also supports collections of objects,


in Javascript these collections are represented as arrays of objects.

Every HTML element has a childNodes collection. The document object has collections forms, images, and links in addition to childNodes.

11

IE supports the document.all collection, which includes an object for every element (tag) in the document.
this is not supported by the W3C DOM standard and is no longer supported by Netscape/Mozilla.

It's best to avoid using document.all, but you are likely to see it used in scripts

12

<SCRIPT> var txt=""; for (var i=0; i<document.images.length;i++) { image = document.images[i]; name = image.getAttribute("src"); txt = txt + name +"<BR>"; } document.writeln("Here are the images found:<BR>\n"); document.write(txt); </SCRIPT>

Add this to the bottom of any HTML document

13

childNodes: just immediate descendants (so subelements are not in the collection). Each member of the collection has it's own childNodes collection! You can write a recursive function that can be used to display the structure of a document by looking through the childNodes collections.

14

Style properties can be accessed through the DOM.


and can be changed in response to user generated events. document.body.style.backgroundColor="blue"; for (i=0;i<document.childNodes.length;i++) { document.childNodes[i].style.fontFamily= "Courier"; }

15

You can also mess with CSS position properties


<H3 ID=joe STYLE="position:absolute; left:0> Hi Joe</H3> <SCRIPT> document.getElementById(joe).style.left = 200; </SCRIPT> dom4.html
16

How to access objects that correspond to elements of the document. by ID, or in collections. How to know what the various object attributes are that change document element properties
need to look up the names in a DOM reference.

17

It is possible to have the browser run JavaScript programs in response to certain events:
user events (moving mouse, clicking, keypress, copy/paste, etc). document/window events (loading, unloading, resizing, scrolling, etc). form submission timed events

18

The onLoad event is triggered when an element is loaded by the browser. You can put an onLoad handler in the BODY tag:
<BODY onLoad="alert('Welcome');"> <H1>A title</H1> <P>Here is a paragraph
dom5.html
19

<SCRIPT> function start() { window.setInterval("updateTime()",1000); } var seconds=0; function updateTime() { seconds++; document.getElementById("time").innerHTML = seconds; } </SCRIPT> <BODY onLoad="start();"> <H1>Sample Document</H1> <H3>You have been here <B ID=time>0</B> seconds.</H3>

20

Schedules the JavaScript program prog to run at a time delay ms. in the future and at regular intervals after that. prog must be a string (that contains JavaScript code). You can stop the code from running with the help of window.clearInterval()

21

The onMouseMove event is triggered whenever the mouse is moving. Can get at the x,y position using the event object. Here is the example that uses this event to display current mouse coordinates when over a specific element of the document: mousemove.html

22

Whenever an event causes JavaScript code to run, an object named event is created. You can find out about the event using this object.
the previous example used clientX and clientY.

23

clientX, clientY : coordinates of the

mouse.
currentTarget: the object that caused the

event (not supported by IE). type: the name of the event


timeStamp

eventobject.html
24

onMouseOver,onMouseOut
mouse moves over or leaves an element.

onHelp
user asks for help (F1 or browser help button).

onKeyDown, onKeyUp, onKeyPress


keyboard events

onUnLoad
element (could be the document) is unloaded (closed).

25

You can use the DOM to get the value of a form field, or to set the value of a form field. Assign an ID to each form field.
use the value attribute to access the current value.

26

Name: <INPUT ID=nfield TYPE=TEXT><BR> <INPUT TYPE=BUTTON VALUE="Check" onClick="validate();"> <SCRIPT> function validate() { fld = document.getElementById("nfield"); if (fld.value != "Dave") { alert("The name you typed is wrong"); fld.value="Dave"; } }

formexample.html
27

new object comes into existence via the new operator paired with the Object constructor. Creating an object is as easy as var shinyAndNew = new Object(); Properties of objects Like their server-side counterparts, JavaScript objects can contain data and possess methods

Unlike those server-side brethren, these elements arent pre-declared for an object; we create them dynamically as needed. Take a look at the following code fragment:
var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005,3,12)

When referencing properties, we can chain references to properties of objects serving as the properties of a parent object
var owner = new Object(); owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner;

To access the nested property, we write


var ownerName = ride.owner.name;

More compact and easier to visually scan.

This notation, which has come to be termed JSON (JavaScript Object Notation1),

A JavaScript object is an unordered collection of properties. Properties consist of a name and a value. Objects can be declared using object literals. Top-level variables are properties of window.

Functions in JavaScript are considered objects like any of the other object types that are defined in JavaScript, such as Strings, Numbers, or Dates. Like other objects, functions are defined by a JavaScript constructorin this case Functionand can be Assigned to variables Assigned as a property of an object Passed as a parameter Returned as a function result Created using literals

Defining function
function doSomethingWonderful() { alert('does something wonderful'); } doSomethingWonderful = function() { alert('does something wonderful'); }

Lets consider the following code:


function hello() { alert('Hi there!'); } setTimeout(hello,5000);

When the timer expires, the hello function is called. Because the setTimeout() method makes a call back to a function in our own code, that function is termed a callback function.

Object with Functions

Object with Functions

closure is a Function instance coupled with the local variables from its environment that are necessary for its execution When a function is declared, it has the ability to reference any variables that are in its scope at the point of declaration. These variables are carried along with the function even after the point of declaration has gone out of scope, closing the declaration.

closure is a Function instance coupled with the local variables from its environment that are necessary for its execution When a function is declared, it has the ability to reference any variables that are in its scope at the point of declaration. These variables are carried along with the function even after the point of declaration has gone out of scope, closing the declaration.

Adding dynamic rows to a form on click of Button Selecting value from select and moving it to hidden field.

Whats the problem with JavaScript?

JavaScript was a initially introduced in Netscape 2.0B3 in Dec 1995, a.k.a. Mocha, LiveScript, Jscript, however, its official name is ECMAScript

JavaScript is a C-family, worlds worst named, extremely powerful language (not a script), totally unrelated to Java

JavaScript is a weakly typed, classless, prototype based OO language, that can also be used outside the browser. It is not a browser DOM.

The worlds most misunderstood programming language.

(Douglas Crockford)

Browser DOM really sucks, and this is where jQuery comes to rescue.

Introduction to jQuery

A Quality of Life by jQuery:


$(#firstName).text(Joe Black); $(button).click(function() {alert Clicked;}); $(.content).hide(); $(#main).load(content.htm); $(<div/>).html(Loading).appendTo(#content);

Very compact and fluent programming model

jQuery is a lightweight, open-source JavaScript library that simplifies interaction between HTML and JavaScript

It was and still being developed by John Resig from Mozilla and was first announced in January 2006

It has a great community, great documentation, tons of plugins, and it was recently adopted by Microsoft

Getting Started

Download the latest version from http://jquery.com

Reference it in your markup

<script src=jquery.js/>

No need to reference the vsdoc.js

Reference it in your JS files:

///<reference path=jquery.js/>

or just drag it into the file

You can also reference it from Google

<script src=http://ajax.googleapis.com/ ajax/libs/jquery/1.2.6/ jquery.min.js> </script>

jQuery Core Concepts

The Magic $() function

var el = $(<div>)

The Magic $() function

$(window).width()

Manipulate existing DOM elements

The Magic $() function

$(div).hide();

Selects document elements (more in a moment)

The Magic $() function

$("p a")
retrieve the group of links nested inside a <p> element

$("div.notLongForThisWorld").fadeOut();
fade out all <div> elements with the CSS class notLongForThisWorld

Selects document elements (more in a moment)

we need a way to wait until DOM elements of the page are fully loaded before those operations execute. In the zebra-striping example, the entire table must load before striping can be applied. Traditionally, the onload handler for the window instance is used for this purpose, executing statements after the entire page is fully loaded. T Syntax is typically something like
window.onload = function() { $("table tr:nth-child(even)").addClass("even"); };

we need a way to wait until DOM elements of the page are fully loaded before those operations execute. In the zebra-striping example, the entire table must load before striping can be applied. Traditionally, the onload handler for the window instance is used for this purpose, executing statements after the entire page is fully loaded. T Syntax is typically something like
window.onload = function() { $("table tr:nth-child(even)").addClass("even"); };

This causes the zebra-striping code to execute after the document is fully loaded. Unfortunately, the browser not only delays executing the onload code until after the DOM tree is created but also waits until after all images and other external resources are fully loaded and the page is displayed in the browser window. As a result, visitors can experience a delay between the time that they first see the page and the time that the onload script is executed.

A much better approach would be to wait only until the document structure is fully parsed and the browser has converted the HTML into its DOM tree form before executing the script to apply the rich behaviors

we can use this technique multiple times within the same HTML document Browser will execute all of the functions we specify in the order that they are declared within the page. In contrast, the windows onload technique allows for only a single function

The Magic $() function


$(function(){}); Fired when the document is ready for programming. Better use the full syntax: $(document).ready(function(){});

The full name of $() function is

jQuery(div);

It may be used in case of conflict with other frameworks.

The library is designed to be isolated


(function(){ var jQuery=window.jQuery=window.$=function(){ // }; })();

jQuery uses closures for isolation

Avoid $() conflict with other frameworks

var foo = jQuery.noConflict(); // now foo() is the jQuery main function foo(div).hide();

// remove the conflicting $ and jQuery var foo = jQuery.noConflict(true);

jQuerys programming philosophy is: GET >> ACT $(div).hide() $(<span/>).appendTo(body) $(:button).click()

Almost every function returns jQuery, which provides a fluent programming interface and chainability:
$(div).show() .addClass(main) .html(Hello jQuery);

Selector that resulted in single matched elements,

$("#someElement").html("I have added some text to an element"); or $("#someElement")[0].innerHTML = "I have added some text to an element";

Selector that resulted in multiple matched elements,


$("div.fillMeIn).html("I have added some text to a group of nodes"); Is Same as var elements = $("div.fillMeIn"); for(i=0;i<elements.length;i++) elements[i].innerHTML = "I have added some text to a group of nodes";

$("p:even"); This selector selects all even <p> elements. $("tr:nth-child(1)"); This selector selects the first row of each table. $("body > div"); This selector selects direct <div> children of <body>.

Three Major Concepts of jQuery

The $() function

Get > Act

Chainability

jQuery Selectors

All Selector

$(*)

// find everything

Selectors return a pseudo-array of jQuery elements

Basic Selectors
By Tag: $(div) // <div>Hello jQuery</div> By ID: $(#usr) // <span id=usr>John</span> By Class: $(.menu) // <ul class=menu>Home</ul> Yes, jQuery implements CSS Selectors!

More Precise Selectors

$(div.main)

// tag and class

$(table#data) // tag and id

Combination of Selectors
// find by id + by class $(#content, .menu) // multiple combination $(h1, h2, h3, div.content)

Hierarchy Selectors
$(table td) $(tr > td) $(label + input) $(#content ~ div) // descendants // children // next // siblings

Selection Index Filters


$(tr:first) $(tr:last) $(tr:lt(2)) $(tr:gt(2)) $(tr:eq(2)) // first element // last element // index less than // index gr. than // index equals

Visibility Filters

$(div:visible) // if visible $(div:hidden) // if not

Attribute Filters
$(div[id]) $(div[dir=rtl]) $(div[id^=main]) $(div[id$=name]) $(a[href*=msdn]) // has attribute // equals to // starts with // ends with // contains

Forms Selectors
$(input:checkbox) $(input:radio) $(:button) $(:text) // checkboxes // radio buttons // buttons // text inputs

Forms Filters
$(input:checked) $(input:selected) $(input:enabled) $(input:disabled) // checked // selected // enabled // disabled

Find Dropdown Selected Item


<select name=cities> <option value=1>Tel-Aviv</option> <option value=2 selected=selected>Yavne</option> <option value=3>Raanana</option> </select>

$(select[name=ddl] option:selected).val()

if we want to select only enabled and checked check boxes, we could use
:checkbox:checked:enabled.

Document Traversal

Generating HTML

$(<div>Hello</div>)
Generates HTML ready to be added

A Selector returns a pseudo array of jQuery objects

$(div).length $(div).size()

Returns number of selected elements. It is the best way to check selector.

Getting a specific DOM element

$(div).get(2) or $(div)[2]

Returns a 2nd DOM element of the selection

Using Index

var n = $('img').index($('img#findMe'));

ordinal index of an image with the id of findMe within the entire set of images in a page.

Getting a specific jQuery element

$(div).eq(2)

Returns a 2nd jQuery element of the selection

Adding Element

$('img[alt]').add(<div>Hi </div>)

Filters out elements from the wrapped set using a passed selector expression, or a filtering function. Parameters expression (String|Function) Specifies a jQuery selector used to remove all elements that do not match from the wrapped set, or a function that makes the filtering decision. This function is invoked for each element in the set, with the current element set as the function context for that invocation. Any element that returns an invocation of false is removed from the set. Returns The wrapped set.

creates a wrapped set of all <td> elements and then invokes the function passed to the filter() method for each, with the current matched elements as the this value for the invocation. The function uses a regular expression to determine if the element content matches the described pattern
$('td').filter(function(){ return this.innerHTML.match(/^\d+$/) } )

$('img').addClass('seeThrough').filter('[title*=dog]).add Class('thickBorder')

Selects all images and applies the seeThrough class to them and then reduces the set to only those image elements whose title attribute contains the string dog before applying another class named thickBorder. The result is that all the images end up semitransparent, but only the tan dog gets the thick border treatment.

$.each(container,callback) Iterates over the items in the passed container, invoking the passed callback function for each. Parameters container (Array|Object) An array whose items or an object whose properties are to be iterated over. callback (Function) A function invoked for each element in the container. If the container is an array, this callback is invoked for each array item; if its an object, the callback is invoked for each object property. The first parameter to this callback is the index of the array element or the name of the object property. The second parameter is the item or property value. The function context (this) of the invocation is also set to the value passed as the second parameter. Returns The container object.

each(fn) traverses every selected element calling fn()


var sum = 0; $(div.number).each( function(){ sum += (+this.innerHTML); });

this is a current DOM element

each(fn) also passes an indexer

$(table tr).each( function(i){ if (i % 2) $(this).addClass(odd); });

$(this) convert DOM to jQuery i - index of the current element

each(fn) traverses every selected element calling fn()


var anArray = ['one','two','three']; $.each(anArray,function(n,value) { //do something here }); var anObject = {one:1, two:2, three:3}; $.each(anObject,function(name,value) { //do something here }); this is a current DOM element

Traversing HTML
.next(expression) // next sibling

.prev(expression)// previous sibling .siblings(expression) // siblings .children(expression) // children .parent(expression) // parent

Traversing HTML - Examples

// Change CSS to odd for all the even cells in Table $('table tr').each(function (i){ if(i%2) $(this).children(':even') .addClass("odd"); } );

Check for expression


$(table td).each(function() { if ($(this).is(:first-child)) { $(this).addClass(firstCol); } });

$.grep(array,callback,invert) Traverses the passed array invoking the callback function for each element. The return value of the callback function determines if the value is collected into a new array returned as the value of the $.grep() function. If the invert parameter is omitted or false, a callback value of true causes the data to be collected. If invert is true, a callback value of false causes the value to be collected. The original array isnt modified.

Grep in selected

// Returns Array having value > 100 var bigNumbers = $.grep(originalArray, function(value) { return value > 100; }); OR var bigNumbers = $.grep(originalArray,'a>100');

Grep in selected

// Returns Array having value > 100 var bigNumbers = $.grep(originalArray, function(value) { return value > 100; }); OR var bigNumbers = $.grep(originalArray,'a>100');

Grep in selected
// Returns Array having Bad Zip codes var badZips = $.grep( originalArray, function(value) { return value.match(/^\d{5}(-\d{4})?$/) != null; }, true);

Find in selected

// select paragraph and then find // elements with class header inside $(p).find(.header).show();

$.map(array,callback) Iterates through the passed array, invoking the callback function for each array item and collecting the return values of the function invocations in a new array. callback (Function|String) A function whose return values are collected in the new array returned as the result of a call to the $.map() function. This function is passed two parameters: the current data value and the index of that value within the original array. A string can also be passed thats converted into the callback function.

Map Examples

//Filter only Numbers var strings = ['1','2','3','4','S','6']; var values = $.map(strings,function(value){ var result = new Number(value); return isNaN(result) ? null : result; });

Advanced Chaining
$(<li><span></span></li>) // li .find(span) // span .html(About Us) // span .andSelf() // span, li .addClass(menu) // span,li .end() // span .end() // li .appendTo(ul.main-menu);

Get Part of Selected Result

$(div) .slice(2, 5) .not(.green) .addClass(middle);

val() Returns the value property of the first element in the matched set. When the element is a multi-select element, the returned value is an array of all selections. Parameters none Returns The fetched value or values.
127

Examples
$("#textbox1").val() // Gets value of Textbox $('[name=radioGroup]:checked').val() //Value of radio buttons which are checked var mupltipleSelection = $("#MulipleSelect").val(); //Selects value in array

HTML Manipulation

Getting and Setting Inner Content

$(p).html(<div>Hello $!</div>);

// escape the content of div.b $(div.a).text($(div.b).html());

Getting and Setting Values


// get the value of the checked checkbox $(input:checkbox:checked).val(); // set the value of the textbox $(:text[name=txt]).val(Hello); // select or check lists or checkboxes $(#lst).val([NY,IL,NS]);

Handling CSS Classes


// add and remove class $(p).removeClass(blue).addClass(red);

// add if absent, remove otherwise $(div).toggleClass(main);

// test for class existance if ($(div).hasClass(main)) { // }

Inserting new Elements


// select > append to the end $(h1).append(<li>Hello $!</li>); // select > append to the beginning $(ul).prepend(<li>Hello $!</li>);

// create > append/prepend to selector $(<li/>).html(9).appendTo(ul); $(<li/>).html(1).prependTo(ul);

The disposition of the original elements depends on the number of elements serving as the target of the append. If there is a single target, the element is removed from its original locationperforming a move operation of the original element to a new parent. In the case where there are multiple targets, the original element remains in place and copies of it are appended to each of the targetsa copy operation.

Replacing Elements
// select > replace $(h1).replaceWith(<div>Hello</div>);

// create > replace selection $(<div>Hello</div>).replaceAll(h1);

Replacing Elements while keeping the content


$(h3).each(function(){ $(this).replaceWith(<div> + $(this).html() + </div>); });

Deleting Elements
// remove all children $(#mainContent).empty();

// remove selection $(span.names).remove(); // change position $(p).remove(:not(.red)) .appendTo(#main);

Handling attributes
$(a).attr(href,home.htm); // <a href=home.htm></a>

// set the same as the first one $(button:gt(0)).attr(disabled, $(button:eq(0)).attr(disabled)); // remove attribute - enable $(button).removeAttr(disabled)

Handling attributes
$("a[href^=http]").attr("target","_blank"); // All External Links open in New Window

Setting multiple attributes


$(img).attr({ src : /images/smile.jpg, alt : Smile, width : 10, height : 10 });

CSS Manipulations
// get style $(div).css(background-color); // set style $(div).css(float, left); // set multiple style properties $(div).css({color:blue, padding: 1em margin-right: 0, marginLeft: 10px});

Dimensions
// get window height var winHeight = $(window).height(); // set element height $(#main).height(winHeight);
//.width() element //.innerWidth() .width() + padding //.outerWidth() .innerWidth() + border //.outerWidth(true) including margin

The default unit is Pixel (px)

Positioning
// from the document $(div).offset().top; // from the parent element $(div).position().left; // scrolling position $(window).scrollTop();

What and Why Ajax Ajax building blocks Sample code Ajax Real time applications Ajax Usage Scenario Ajax Caveats Ajax Best Practices Ajax frameworks
Private and Confidential

Request Response Paradigm


User has to wait for response. Network Latency, amount of business logic involved etc., will impact performance Performance tuning matters! Special care and effort involved in building high responsive application

Click, wait, and refresh user interaction


Page refreshes from the server needed for all events, data submissions, and navigation

Page-driven: Workflow is based on pages


Page-navigation logic is determined by the server
Private and Confidential

Desktop Applications are known for Rich User Experience. For example SpreadSheet Application. Characteristics:
program responses intuitively and quickly program gives a user meaningful feedback's instantly

Things happen naturally


No need to click a button or a link to trigger an event
Private and Confidential

Oh! I lost Track!! What


a poor site! So Many hyperlinks to click to complete small piece of business Can there be any magic to change it to better user experience??
Thanks! Now AJAX came to rescue

Endless Wait !!!

Oh!! It is boring. Even for small change, the entire page is refreshing!!!!

I spend most time in web applications

Dull Web Experience

AJAX
Private and Confidential

Interesting browsing experience

More pressing need for current web applications to provide Web applications differed from their web site ancestors in that they provided an instant service to their users, not just information. Whether for business process management or personal interests, developers were forced to create new interaction paradigms as users came to expect richer functionality. Web took a bold step forward through AJAX, shattering the traditional usage model that required a full page load every time new data or a new part of the applications logic was accessed. Companies began to experiment with dynamic reloading of portions of web pages, transmitting only a small amount of data to the client, resulting in a faster, and arguably better, user experience.

Private and Confidential

Ajax (Asynchronous JavaScript + XML)


A term coined by coined by Jesse James Garrett of Adaptive Path. Some parts of Ajax have been previously described as Dynamic HTML and remote scripting.

What is AJAX? Ajax isnt a technology. Its really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:
standards-based presentation using XHTML and CSS; dynamic display and interaction using the Document Object Model data interchange and manipulation using XML and XSLT asynchronous data retrieval using XMLHttpRequest JavaScript binding everything together

Private and Confidential

within a browser, there is AJAX engine

Private and Confidential

Pros
Improved user Experience AJAX can be used instead of Refresh header to Simulate Server push using polling technique. More useful for Real-time applications Used for Caching data

Cons
Back and Forward buttons do not tie in to XmlHttpRequests, so broken History Records. Needs user to be aware that AJAX calls are executing in the background; otherwise user might hit the button many times creating duplicate requests.
Private and Confidential

Private and Confidential

An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary an Ajax engine between the user and the server. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine written in JavaScript and usually tucked away in a hidden frame. AJAX engine is responsible for both rendering the interface the user sees and communicating with the server on the users behalf. The Ajax engine allows the users interaction with the application to happen asynchronously independent of communication with the server. So NO MORE staring at a blank browser window and an hourglass icon, waiting around for the server to do something.

Private and Confidential

Private and Confidential

Real-time server-side input form data validation


User IDs, serial numbers, postal codes Removes the need to have validation logic at both client side for user responsiveness and at server side for security and other reasons

Auto-completion
Email address, name, or city name may be autocompleted as the user types

Master detail operation


Based on a user selection, more detailed information can be fetched and displayed
Private and Confidential

Advanced GUI widgets and controls


Controls such as tree controls, menus, and progress bars may be provided that do not require page refreshes

Refreshing data
HTML pages may poll data from a server for up-todate data such as scores, stock quotes, weather, or application-specific data

Simulating server side notification


An HTML page may simulate a server-side notification by polling the server in the background

Partial Submit of data.


Private and Confidential

<script language="javascript" type="text/javascript"> var xRequest=null; function createXMLHttpRequest() { try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } } if (request == null) alert("Error creating request object!"); }

} </script>

Private and Confidential

XMLHttpRequest objects open method will initiate a request to the specific URL.
XMLHttpRequest.open(mode,url,asynchronous); Mode can be GET / POST Asynchronous a flag indicating whether the request to be made asynchronously or not;

XMLHttpRequests send method is used to send the data. XMLHttpRequests onreadystatechange is used to hook the callback handler to the request.
This callback handler will be called by the browser when a response is received.
Private and Confidential

Pass true for asynchronous and false for synchronous.

function postRequest(strURL) { var xmlHttp; if (window.XMLHttpRequest) { // Mozilla, Safari, ... var xmlHttp = new XMLHttpRequest(); }else if (window.ActiveXObject) { // IE var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.open('POST', strURL, true); xmlHttp.setRequestHeader('Content-Type', 'application/x-www-formurlencoded'); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { updatepage(xmlHttp.responseText); } } xmlHttp.send(strURL); }
Private and Confidential

function updatepage(str){ document.getElementById("result").innerHTML = "<font color='red' size='5'>" + str + "</font>";; } function SayHello(){ var usr=window.document.f1.username.value; var url="sayhello.php?usr="+usr; postRequest(url); } <input value="Say Hello" type="button" onclick='JavaScript:SayHello()' name="showdate"> <div id="result" align="center"></div>
Private and Confidential

As the callback handler is hooked to onReadyStateChange, ot gets called several times during Request Response life cycle. So it is mandatory to check if the response is complete before updating the page

ReadyState Values Value State 0 1 2 3 4 Description Uninitialized Open() not called yet Loading Loaded Interactive Complete Open() executed Send() executed Server returned chunk of data Request is complete and server finihed data

Private and Confidential

Private and Confidential

Private and Confidential

Private and Confidential

Provide a statement early in the page that indicates the use of AJAX technologies and informs the user that dynamic updates will occur. Provide notification of focus shift
Do not automatically shift focus on the page when an update occurs. Changing focus without warning can be distracting for some users, especially if there is no easy mechanism to return to the previous position.

Consider the use of color or a change in font size or weight to temporarily highlight the area which has updated. Ajax applications should send and receive as little information as possible to and from the server.
Private and Confidential

Make navigation easy


Provide links to portions of the page that are dynamically updated. If the site relies on the update of several areas of the page at different frequencies, provide a way to quickly navigate to each section. This set of links should be easily reached from the top or bottom of the page to make navigation to them quick and easily repeatable.

Whenever possible, update existing elements with new content rather than creating and adding new high-level elements to the page. Separate Behavior from Content and Presentation
Behaviour JavaScript Content - HTML / XML Presentation CSS / XSLT

Have Javascript and CSS in external file and link them

inspect the readyState or status fields of the object in the callback Document output, parameters, and dependencies

Private and Confidential

The Browser Was Never Meant For Ajax


Ajax pushes the browser nearly beyond its limits without powerful 3rd party development tools, designing clean Javascript software of any size requires some genuine discipline and effort. Ajax debugging applications in multiple browsers is difficult

Ajax Is More Involved Than Traditional Web Design and Development.


The loss of HTML user interface conventions almost limitless potential for hidden or latent functionality programmatic creation of page elements instead of declarative

Testing AJAX applications are difficult due to its asynchronous nature.


Private and Confidential

What to do if XMLHttpRequest is not available? Usability concerns


User might not understand that the browser has submitted the request in background. Usual feedback mechanisms of the hourglass cursor and spinning browser "throbber" do not apply for XMLHttpRequests

Server load
Implementing an Ajax UI in place of a regular forms-based one may dramatically increase the number of requests made to the server.

Dealing with asynchrony


It's very important to understand that there is no guarantee that XMLHttpRequests will complete in the order they were dispatched. Indeed, you should assume that they will not and design your application with this in mind . This requires extra precautions to be taken

AJAX brings more security threats than the traditional Web application
Private and Confidential

Client Side JavaScript Library


DOJO Prototype

RMI Like Remoting via Proxy


DWR

AJAX Wrapper
JMAKI (MAKI means Wrap in Japanese)

Java to Javascript / HTML translator


GWT

MVC Server Side Scripting


Phobos

Web Application framework with AJAX Extension


Shale
Private and Confidential

1. The technology used for Processing response


A. CSS B. DOM C. XMLHttpRequest D. HTML E. Javascript
Private and Confidential

2. Technology used for sending request asynchronously


A. CSS B. DOM C. XMLHttpRequest D. HTML E. Javascript
Private and Confidential

3. Applications that uses AJAX


A. CSS B. Google map C. ServerSide.com D. None of the above

Private and Confidential

4. Synchronous calls can also be made using AJAX


A. True B. False

Private and Confidential

5. Ajax Uses Javascript to bind Ajax building blocks together


A. True B. False

Private and Confidential

6. Name the method of XMLHttpObject to send data to server


A. Send B. Open C. Invoke D. Post

Private and Confidential

7. How to hook the callback handler?


A. Using XMLHttpRequests onReadyStateChanged

method. B. Using XMLHttpRequests readyStateChanged method. C. Using XMLHttpRequests hookCallbackHandler method. D. Using XMLHttpRequests stateChanged method.
Private and Confidential

8. ReadyState value for response complete:


A. 1. B. 2. C. 3. D. 4.

Private and Confidential

9. Ajax User Experience: Select true statements.


A. Notification to the user that the page uses AJAX. B. Always use xmlHttpRequest.open() with false as

a last argument value. C. Inspect ready state or status fields of the object in the callback. D. None of the above.
Private and Confidential

http://www.ibm.com/developerworks/java/lib rary/j-ajax1/index.html http://web2.socialcomputingmagazine.com/s even_things_every_software_project_needs_ to_know_about_ajax.htm professional-ajax-2nd-edition Apress Press

Private and Confidential

JSON (JavaScript Object Notation) is a lightweight datainterchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. JSON is built on two structures:

JSON is built on two structures:


A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma)..

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

value can be a string in double quotes, or a number, or true or false or null, or an object or an array

<menu id="file" value="File"> <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup> </menu>

{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}

var cobblers = [ {"filling": "peach", "timeToBake": 30 }, {"filling": "cherry", "timeToBake": 35 }, {"filling": "blueberry", "timeToBake": 30} ];

Java script objects in code

{ "cobblers": [ {"filling": "peach", "timeToBake": 30 }, {"filling": "cherry", "timeToBake": 35 }, {"filling": "blueberry", "timeToBake": 30} ] }

Java Script object notation over the wire

AJAX with jQuery

Loading content
$(div).load(content.htm); // passing parameters $(#content).load(getcontent.aspx, {id:33, type:main});

Example BootCloset1

Loading content
serialize() Creates a properly formatted and encoded query string from all successful form elements in the wrapped set, or all successful form elements of forms in the wrapped set. Parameters none Returns The formatted query string.

Loading content
serializeArray() Collects the values of all successful form controls into an array of objects containing the names and values of the controls. Parameters none Returns The array of form data.

Sending GET/POST requests


$.get(test.aspx, {id:1}, function(data){alert(data);});

$.post(test.aspx, {id:1}, function(data){alert(data);});

Sending GET/POST requests


$.get(url,parameters,callback,type) Initiates a GET request to the server using the specified URL with any passed parameters as the query string. Parameters url (String) The URL of the server-side resource to contact via the GET method. parameters (String|Object|Array) Specifies any data thats to be passed as request parameters. This parameter can be a string that will be used as the query string, an object whose properties are serialized into properly encoded parameters to be passed to the request, or an array of objects whose name and value properties specify the name/value pairs. callback (Function) An optional function invoked when the request completes successfully. The response body is passed as the first parameter to this callback, interpreted according to the setting of the type parameter, and the text status is passed as the second parameter. A third parameter contains a reference to the XHR instance. type (String) Optionally specifies how the response body is to be interpreted; one of html, text, xml, json, script, or jsonp. Returns The XHR instance.

Retrieving JSON Data


$.getJSON(users.aspx, {id:1}, function(users) { alert(users[0].name); });

Retrieving JS Files
$.getScript(script.js, function() { doSomeFunction(); });

Examples
GetLoad.html GetJson.html GetCities.html AjaxForm.html

Events

When the DOM is ready


$(document).ready(function(){ // });

Fires when the document is ready for programming. Uses advanced listeners for detecting. window.onload() is a fallback.

Attach Event
// execute always $(div).bind(click, fn); // execute only once $(div).one(click, fn);

Possible event values:

blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error
(or any custom event)

jQuery.Event object

Detaching Events

$(div).unbind(click, fn);

(Unique ID added to every attached function)

Events Triggering

$(div).trigger(click);

Triggers browsers event action as well. Can trigger custom events. Triggered events bubble up.

Events Helpers
// attach / trigger elem.blur(fn) / elem.blur() elem.focus(fn) / elem.focus() elem.click(fn) / elem.click() elem.change(fn) / elem.change() And many others

Preventing Browser Default Action


// use different triggering function $(div).triggerHandler(click); // prevent default action in handler function clickHandler(e) { e.preventDefault(); } // or just return false function clickHandler(e) {return false;}

Preventing Bubbling
// stop bubbling, keep other handler function clickHandler(e) { e.stopPropagation(); } // stop bubbling and other handlers function clickHandler(e) { e.stopImmediatePropagation(); } // or just return false function clickHandler(e) {return false;}

Live Events
// attach live event (div).live(click, fn); // detach live event (div).die(click, fn);
Currently supported events:

click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup

Effects

Showing or Hiding Element


// just show $(div).show(); // reveal slowly, slow=600ms $(div).show(slow); // hide fast, fast=200ms $(div).hide(fast); // hide or show in 100ms $(div).toggle(100);

Sliding Elements
$(div).slideUp(); $(div).slideDown(fast); $(div).slideToggle(1000);

Fading Elements
$(div).fadeIn(fast); $(div).fadeOut(normal); // fade to a custom opacity $(div).fadeTo (fast, 0.5);

Fading === changing opacity

Detecting animation completion


$(div).hide(slow, function() { alert(The DIV is hidden); });

$(div).show(fast, function() { $(this).html(Hello jQuery); }); // this is a current DOM element

Every effect function has a (speed, callback) overload

Custom Animation
// .animate(options, duration) $(div).animate({ width: 90%, opacity: 0.5, borderWidth: 5px }, 1000);

Chaining Animation

$(div).animate({width: 90%},100) .animate({opacity: 0.5},200) .animate({borderWidth: 5px});

By default animations are queued and than performed one by one

Controlling Animations Sync


$(div) .animate({width: 90%}, {queue:false, duration:1000}) .animate({opacity : 0.5});

The first animation will be performed immediately without queuing

Extending the Library

Adding Methods
// definition jQuery.fn.printLine = function(s) { return jQuery(this).each(function() { this.append(<div>+ s +</div>); }); }; // usage $(#log).printLine(Hello);
Do not use $ in the method
(at least not until next slide)

Closure to solve the $ issue


(function ($) { jQuery.fn.printLine = function(s) { return $(this).each(function() { this.append(<div>+ s +</div>); }); }; })(jQuery);

One more Example


(function($){ $.fn.makeItBlue = function() { return this.css('color','blue'); }; })(jQuery);

Defaults and Options


It's a best practice to have default settings that can get extended (using $.extend) when the plugin is invoked. So instead of calling a plugin with a large number of arguments, you can call it with one argument which is an object literal of the settings you would like to override.

$.fn.tooltip = function( options ) { var settings = $.extend( { 'location' : 'top', 'background-color' : 'blue' }, options); return this.each(function() {

Namespacing
Under no circumstance should a single plugin ever claim more than one namespace in the jQuery.fn object. function( $ ){ $.fn.tooltip = function( options ) { Bad }; $.fn.tooltipShow = function( ) { Bad };

Namespacing
function( $ ){

var methods = { init : function( options ) { }, show : function( ) { }, };

Namespacing
$.fn.tooltip = function( method ) { // Method calling logic if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); }

Custom Selectors
$.expr[:].test = function(o, i, m, s) { // o current object in the selection // i loop index in the stack // m meta data about your selector // s stack of all the elements // return true to include the element // return false to exclude the element };

Example

Show more Widget Readonly Plugin Makeit Blue Namespace example

Do not use $ in the method


(at least not until next slide)

More things to explore


More Functionality on every aspect URL parameters parser Browser and features detection Data Cache Utilities Helper functions Various Plug-ins

Where to go next

jQuery web-site: http://jquery.com jQuery API: http://api.jquery.com Many many blogs jQuery in Action book:

Contact me

Blog: http://blogs.microsoft.co.il/blogs/linqed Email: vlad@netwise.co.il

Thank YOU!

dojo.xhrGet( { // The following URL must match that used to test the server. url: "ajax.json",

handleAs: "json",
load: function(responseObject, ioArgs) { // Prints "peach" console.dir(responseObject.cobblers[0].filling); return responseObject; } // More properties for xhrGet... });

An interpreted programming language with object oriented capabilities. Not Java!


Originally called LiveScript, changed to JavaScript as a marketing ploy by Sun and Netscape. Can also be referred to as ECMAScript.

Not simple!
Although it is loosely typed and can be used by web developers in a cookbook fashion (think image rollovers), JavaScript is a fully featured programming language with many advanced features.

When JavaScript is embedded in a web browser, it is referred to as Client Side JavaScript. Contains an extended set of functionality to interface with the web browser DOM (Document Object Model). Objects, such as window and document, and functions, like event detection and handling, are included in Client Side JavaScript.

A framework for Client Side JavaScript. Frameworks provide useful alternatives for common programming tasks, creating functionality which may not be available or cumbersome to use within a language. An open source project, maintained by a group of developers, with a very active support base and thorough, well written documentation.

A substitute for knowing JavaScript


jQuery is extraordinarily useful, but you should still know how JavaScript works and how to use it correctly. This means more than Googling a tutorial and calling yourself an expert.

A solve all
There is still plenty of functionality built into JavaScript that should be utilized! Dont turn every project into a quest to jQuery-ize the problem, use jQuery where it makes sense. Create solutions in environments where they belong.

Cross browser support and detection AJAX functions CSS functions DOM manipulation DOM transversal Attribute manipulation Event detection and handling

JavaScript animation Hundreds of plugins for pre-built user interfaces, advanced animations, form validation, etc Expandable functionality using custom plugins Small foot print

$.func(); or $(selector).func1().func2().funcN();
$ jQuery Object, can be used instead of jQuery selector Selector syntax, many different selectors allowed func Chainable, most functions return a jQuery object () Function parameters

Represented by both $ and jQuery


To use jQuery only, use jQuery.noConflict(), for other frameworks that use $

By default, represents the jQuery object. When combined with a selector, can represent multiple DOM Elements, see next slide. Used with all jQuery functions.

$( html ) Create DOM elements on-thefly from the provided String of raw HTML. $( elems ) Wrap jQuery functionality around single or multiple DOM Elements. $( fn ) A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading.

$( expr, context ) This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements. Default context is document. Used most often for DOM transversal. Selectors will return a jQuery object, which can contain one or more elements, or contain no elements at all.

$( html ) $(<p><a href=index.html>Click here!</a></p>) $ ( elems ) $(document), $(window), $(this) $(document.getElementsByTagName(p)) $ ( fn )


$(function() { alert(Hello, World!) });

$ ( expr, context )
$(p), $(form), $(input) $(p#content), $(#content), $(.brandnew), $(p span.brandnew:first-child, #content) $(p/span), $(p/span[@class=brandnew]), $(p/span:first), $(p:first/span:even) $(input:checkbox[@checked]), $(div:visible p[a]) var xml = <d><it w=h1><nm>One</nm></it><it w=h2><nm>Two</nm></it></d>; $(d it nm:contains(One), xml), $(it[@w^=h],xml)

Attached to the jQuery object or chained off of a selector statement. Most functions return the jQuery object they were originally passed, so you can perform many actions in a single line. The same function can perform an entirely different action based on the number and type of parameters.

$(li:odd).prepend(<span>Changed</span>).css({background:red});
<ul> <li> First item </li> <li> Second item </li> <li> Third item </li> </ul> <ul> <li> <span>Changed</span> First item </li> <li> Second item </li> <li> <span>Changed</span> Third item </li> </ul> <ul> <li style=background:red;> <span>Changed</span> First item </li> <li> Second item </li> <li style=background:red;> <span>Changed</span> Third item </li> </ul>

$(div:hidden).find(.foo).empty().text(Changed).end().show();
<div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Goodbye cruel world. </span> </div> <div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Goodbye cruel world. </span> </div> <div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> </span> </div>

<div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Changed </span> </div>

<div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Changed </span> </div>

<div> <span class=foo> Some text </span> </div> <div style=display:block> <span> More text </span> <span class=foo> Changed </span> </div>

$(span.none).click( function(){ $(this).siblings(:checkbox).removeAttr(checked); } ); $(span.all).click( function(){ $(this).siblings(:checkbox).attr(checked,checked); } );

<div> <span class=all>Select All</span> <span class=none>Select None</span> <input name=chk1 type=checkbox/> <input name=chk2 type=checkbox/> <input name=chk3 type=checkbox/> </div> <div> <span class=all>Select All</span>

or
$(span).click( function(){ if($(this).text()==Select All)) $(this).siblings(:checkbox).attr(checked,checked); else if ($(this).attr(class)==none) $(this).siblings(:checkbox).removeAttr(checked); } );

<span class=none>Select None</span> <input name=chk4 type=checkbox/> <input name=chk5 type=checkbox/> <input name=chk6 type=checkbox/> </div>

jQuery has a series of functions which provide a common interface for AJAX, no matter what browser you are using. Most of the upper level AJAX functions have a common layout:
$.func(url[,params][,callback]), [ ] optional
url: string representing server target params: names and values to send to server callback: function executed on successful communication.

$.func(url[,params][,callback])
$.get $.getJSON $.getIfModified $.getScript $.post

$.ajax, $.ajaxSetup
async beforeSend complete contentType data dataType error global ifModified processData success timeout type url

$(selector), inject HTML


load loadIfModified

$(selector), ajaxSetup alts


ajaxComplete ajaxError ajaxSend ajaxStart ajaxStop ajaxSuccess

<html> <head> <title>AJAX Demo</title> <script type=text/javascript src=jquery.js> </script> <script type=text/javascript> var cnt = 0; $(function(){ $.ajaxSettings({ error:function(){alert(Communication error!);} }); $(:button).click(function(){ var input = {in:$(:textbox).val(),count:cnt}; $.getJSON(ajax.php,input,function(json){ cnt = json.cnt; $(.cnt).text(cnt) $(.msg).text(json.out); }); }); }); </script> </head> <body> <p> Input: <input type=textbox/> <input type=button value=Send/> Output # <span class=cnt></span>: <span class=msg></span> </p> </body> </html>

<?php $output = ; switch($_REQUEST[in]) { case hello: $output = Hello back.; break; case foo: $output = Foo you, too.; break; case bar: $output = Where Andy Capp can be found.; break; case foobar: $output = This is German, right?; break; default: $output = Unrecognized string.; } $count = $_REQUEST[count]+1; echo json_encode( array( out => $output, cnt => $count ) ); exit; ?>

demo ajax demo offer management (prototyping) animation demo

Você também pode gostar