Jquery Ajax
Jquery Ajax
Introduction
Ajax Utilities
• $.ajax({options})
– Makes an Ajax request. Example:
• $.ajax({ url: "address", success: responseHandler});
• The response handler is passed the response text, not the
response object. Don’t forget the “.” before “ajax”!
• load(url)
– Makes
k Ajax
j request andd loads
l d result
l into
i HTML element
l
• $("#some-id").load("address");
g or object
• A data string j is an optional
p second arg
g
• Shortcuts
– $.get, $.post, $.getJSON
• Slightly simpler forms of $.ajax. However, they support
fewer options, so many developers just use $.ajax.
8
Downloading and Installation
• Download
– http://jquery.com/
• For development, use uncompressed file
– E.g.,
g , jquery-1.4.3.js
jq y j
• For deployment, use compressed file
– E.g., jquery-1.4.3.min.js
– For easier upgrades without changing HTML files
• Rename file to jquery.js (or possibly jquery-1.4.js)
• Installation
– Load jquery.js before any JS files that use jQuery
• That’s it: just a single file to load for core jQuery.
• jQuery UI (covered in later tutorial) is a bit more involved
• Online API and tutorials
9 – http://docs.jquery.com/
Browser Compatibility
• Firefox
– 2.0
2 0 or later
l (vs.
( 1.51 5 or later
l for
f Prototype)
P )
• Internet Explorer
– 6.0 or later (does not work in IE 5.5)
• Chrome
– All (i.e., 1.0 or later)
• Safari
– 3.0 or later (vs. 2.0 or later for Prototype)
• Opera
– 9.0 or later (vs. 9.25 or later for Prototype)
• To check
– Run the test suite at http://jquery.com/test/
10
Industry Usage
(Job Postings)
11
Industry Usage
(Google Searches)
12
© 2010 Marty Hall
jQuery Selectors:
Basics
Note: brief intro only. More details in next tutorial section.
Example: Randomizing
Background Colors (JavaScript)
function randomizeHeadings() { Call setRandomStyle function on each h3 element
$("h3")
$( h3 ).each(setRandomStyle);
each(setRandomStyle);
$("h3.green").hide("slow");
} Slowly hide every h3 that has CSS style “green”
function setRandomStyle() {
$(this).addClass(randomStyle());
}
Add “red”, “yellow” or “green” CSS names to each
function randomStyle() {
a sty
var styles
es = [
["red",
ed , "yellow",
ye o , "green"];
g ee ];
return(randomElement(styles));
}
( y) {
function randomElement(array)
var index = Math.floor(Math.random()*array.length);
return(array[index]);
16 }
Example: Randomizing Colors
(JavaScript Continued)
function revertHeadings() {
$("h3
$( h3.green
green")
).show(
show("slow");
slow );
$("h3").removeClass("red").removeClass("yellow")
.removeClass("green");
}
Like smart window.onload. Explained in next section.
$(function() {
$("#b tt 1") li k(
$("#button1").click(randomizeHeadings);
d i H di )
$("#button2").click(revertHeadings);
});
Sets onclick handlers
17
18
Example: Randomizing Colors
(HTML)
…
<head><title>jQuery Basics</title>
<link rel="stylesheet"
During development, renamed jquery-1.4.3.js to jquery.js and used it
href="./css/styles.css" here. For deployment, replaced it with renamed jquery-1.4.3.min.js
type="text/css"/>
<script src="./scripts/jquery.js"
type="text/javascript"></script>
<
<script
i t src="./scripts/jquery-basics.js"
" / i t /j b i j "
type="text/javascript"></script>
</head>
19
Understanding Operations on
Sets of Elements
• Instead of this
function randomizeHeadings() {
$("h3").each(setRandomStyle);
$("h3 green") hide("slow");
$("h3.green").hide("slow");
}
y () {
function setRandomStyle()
$(this).addClass(randomStyle());
}
• Why can’t I simply do this?
function randomizeHeadings() {
$("h3") ddCl ( d St l ())
$("h3").addClass(randomStyle())
$("h3.green").hide("slow");
22
}
© 2010 Marty Hall
$.ajax: Basics
function showAlert(text) {
alert(text);
} This is the response text, not the response object. Use three-argument
version if you need the raw XMLHttpRequest object. Also note that
recent Firefox versions do not let you pass native functions here, so
yyou cannot use alert instead of showAlert for the success p
property.
p y
28
$.ajax Example Code:
HTML
...
<head><title>jQuery and Ajax</title>...
Ajax</title>
<script src="./scripts/jquery.js"
type="text/javascript"></script>
<script src="./scripts/jquery-ajax.js"
/ /
type="text/javascript"></script>
</head>
<body>...
<fieldset>
<legend>$.ajax:
g $ j Basics ((Using
g onclick
handler in HTML)</legend>
<input type="button" value="Show Time"
onclick showTime1() />
onclick='showTime1()'/>
</fieldset>
29
30
$.ajax: Results
31
function showTime1() {
$.ajax({ url: "show-time.jsp", These two functions
success: showAlert, are unchanged from
previous example.
cache: false });
}
function showAlert(text) {
alert(text);
}
33
34
Redoing Time Alert: Results
35
$.ajax:
$ ajax:
Sendingg Data
Three Alternatives
• Explicit string
– S
Supplyl an explicit
li it string
t i for
f data
d t property.t We
W will
ill hardcode
h d d it
in this example, but it can also be built from data in the page
as with earlier Ajax examples.
• $.ajax({url:
$ ajax({url: …, data: "a=foo&b=bar"
a=foo&b=bar , success: …});
});
• Data object
– Supply an object for data property. Property names become
param names andd URL-encoded
URL d d property values
l become
b
param values. URL-encoding of values is automatic.
• var params = { a: "value 1", b: "another value!"};
• $.ajax({url:
$ ajax({url: …, data: params
params, success: …});
});
• String built by “serialize”
– Give id to the form. Give names (not ids) to input elements.
When you call serialize on form, it builds the same query
string as a browser would on normal form submission.
38
• $.ajax({url: …, data: $("#form-id").serialize(), success: …});
The “data” Option with Explicit
String: JavaScript
$(function() {
$("#data button 1") click(showParams1);
$("#data-button-1").click(showParams1);
…
});
function showAlert(text) {
alert(text);
}
Same function used in earlier examples.
function showParams1()
() {
$.ajax({ url: "show-params.jsp",
data: "param1=foo¶m2=bar",
success: showAlert });
}
The cache option is not used since the same data always results in the same response.
39
40
The “data” Option with Explicit
String: JSP
param1 is ${param.param1},
param2 is ${param
${param.param2}.
param2}
All three examples with the "data" option use this same JSP page.
41
42
The “data” Option with Data Object:
JavaScript
$(function() {
$("#data-button-2")
$( #data button 2 ).click(showParams2);
click(showParams2);
…
});
function showAlert(text) {
alert(text);
}
function showParams2() {
a pa
var params
a s =
{ param1: $("#field1").val(),
param2: $("#field2").val() };
$.ajax({
$ j ({ url: "show-params.jsp",
p j p ,
data: params,
success: showAlert });
43 }
44
The “data” Option with Data Object:
JSP
param1 is ${param.param1},
param2 is ${param
${param.param2}.
param2}
All three examples with the "data" option use this same JSP page.
45
46
The “data” Option with String from
“serialize
serialize ”:: JavaScript
$(function() {
$("#data-button-3")
$( #data button 3 ).click(showParams3);
click(showParams3);
…
});
function showAlert(text) {
alert(text);
}
function showParams3() {
$.ajax({
$.aja ({ u
url:
: "show-params.jsp",
s o pa a s.jsp ,
data: $("#data-form").serialize(),
success: showAlert });
}
47
The reason for action="#" on the form is that, technically, the action attribute of form is required. So, just to satisfy
48 formal HTML validators, we put in dummy action value. But, of course, the action is not used in any way.
The “data” Option with String from
“serialize
serialize ”:: JSP
param1 is ${param.param1},
param2 is ${param
${param.param2}.
param2}
All three examples with the "data" option use this same JSP page.
49
50
© 2010 Marty Hall
$.ajax:
$ ajax:
Options
p and Shortcuts
Overview
• Options (almost) always used: url, success
– $.ajax({url: "some-address", success: someFunction});
• success is not strictly required; you might want to just fire
off some data to the server and not display
p y anything
y g
• Common options: example
$.ajax({
url:
l "address",
" dd "
success: successHandlerFunction,
data: { param1: "foo bar", param2: "baz"},
error: errorHandlerFunction,
cache: false,
yp
dataType: "json",
j ,
username: "resig",
password: "scriptaculous-fan" });
52
Options
Name Description Default
async Should
Sh ld the
th requestt be
b asynchronous?
h ? Use
U synchronous
h requests
t with
ith t
true
caution since they lock up the browser.
beforeSend Function to modify XMLHttpRequest object before it is sent (e.g., None
to set custom headers). The XHR is automatically passed to
function.
cache Is browser permitted to cache the page? Set to false if you use GET true
and you could get different responses back from the same data. (except false if
Equivalent to having the server send Cache
Cache-Control:
Control: no
no-cache
cache and dataType is script
Pragma: no-cache. or json)
Options (Continued)
Name Description Default
d t Filt
dataFilter R
Response-data
d t sanitizing
iti i function.
f ti R l used.
Rarely d N
None
dataType The format in which to pass the response to the handler function. html , xml,
Legal values are text, html (same as text except embedded scripts or json
are run),
), xml,, jjson,, jjsonpp ((JSON with Padding),
g), and script
p (makes intelligent
(evaluates the response as JavaScript and returns it as plain text). guess)
error Function to be called if request fails. Function is passed 3 args: the None
XHR object, a string describing the error type, and an optional
exception object.
object Possible values for the second argument are null,
null
"timeout", "error", "notmodified" and "parsererror".
global jQuery lets you set global defaults for various handlers: should they true
be used if set?
ifModified Should the request be considered successful only if the response has false
changed since the last request (based on the Last-Modified header)?
jsonp Override the callback function name in a jsonp request. JSONP is a callback
JSON extension
e tension in which
hich the name of a callback function
f nction is
specified as an input argument of the call itself.
password Username and password to be used in response to HTTP None
54 username authentication request.
Options (Continued)
Name Description Default
processData Should the value of the “data”
data property,
property if an object,
object be turned into true
a URL-encoded query string?
scriptCharset Forces the request to be interpreted as a certain charset. Only for None
requests with dataType of “jsonp” or “script” and type of “GET”.
success Function to be called if request succeeds. Function passed 3 args: None
the data returned from the server (formatted according to the
dataType property), a string describing the status, and the XHR.
ti
timeout
t Timeoutt in
Ti i milliseconds.
illi d If requestt takes
t k longer,
l the
th error handler
h dl Global timeout,
timeout if
will be called instead of the success handler. set via
$.ajaxSetup
traditional Should data with arrays be serialized in traditional manner false
( h ll ) or recursively
(shallow), i l (deep).
(d )
type The HTTP method to use for the request. “get” and “post” are get
main options, but some browsers support other methods.
url The address to request
request. Should be a relative URL
URL. None
xhr Callback for creating your own custom XMLHttpRequest object. ActiveXObject if
available (IE),
XMLHttpRequest
55 otherwise
Simplifying
p y g Insertingg Results
into HTML:
the “load”
load Function
p ( q , resultRegion)
function showResponseText(request, g ) {
if ((request.readyState == 4) &&
(request.status == 200)) {
document.getElementById(resultRegion).innerHTML =
request.responseText;
t T t
}
}
60
Content-Centric Ajax with and
without Toolkits ($.ajax)
($ ajax)
function ajaxResult(address, resultRegion) {
$ ajax({
$.ajax({
url: address,
success: function(text) {
showResponseText(text resultRegion);
showResponseText(text,
}
});
}
61
function insertParams() {
$("#params-result").load("show-params.jsp",
$("#load-form").serialize());
}
63
64
load Example: JSP
param1 is ${param.param1},
param2 is ${param
${param.param2}.
param2}
65
66
© 2010 Marty Hall
Approach
• Server
– Returns JSON object with no extra parens. E.g.:
• { "cto": "Resig ", "ceo": "Gates ", "coo": "Ellison" }
• Code that calls $
$.ajax
ajax
– Specifies dataType of json. E.g.:
• $.ajax({
j ({ url: address, success: handler, dataType:
y "json"
j });
})
• Response handler
– Receives JavaScript data as first argument. No need for
parsing
i or “eval”.
“ l” Must
M bbuild ild HTML from
f result.
l E.g.:
E
• function handler(companyExecutives) {
$("#some-id").html("<b>Chief
( ) ( Technology
gy Officer is " +
companyExecutives.cto + "</b>");
}
68
Strict JSON
• JSON in practice
– Th
The way you would ld type a data
d structure into
i JavaScript.
J S i
– This is what “eval”, Prototype, and jQuery 1.3 support
• Strict JSON according to json.org
json org
– Subset of JavaScript where
• Object property names must be in double quotes
• Strings
St i are represented
t d with
ith double
d bl quotes
t onlyl ((nott
single quotes)
– This is what jQuery 1.4 supports. Since this is what is
clearl described at json.org,
clearly json org you
o should
sho ld follow
follo this
format when sending JSON from the server.
• MIME type
yp for JSON from server
– RFC 4627 says JSON should have "application/json" type
– No known libraries enforce this
69
function showNums() {
$.ajax({ url: "show-nums",
dataType: "json",
success: showNumberList
h N b Li t });
})
} Strings
function showNumberList(jsonData)
( ) {
var list = makeList(jsonData.fg, jsonData.bg,
jsonData.fontSize,
jsonData.numbers);
$("#nums-result").html(list); int
Array of doubles
70 }
JSON Example Code: Auxiliary
JavaScript
function makeList(fg, bg, fontSize, nums) {
return(
listStartTags(fg, bg, fontSize) +
listItems(nums) +
listEndTags());
}
function
f ti li
listStartTags(fg,
tSt tT (f b
bg, f
fontSize)
tSi ) {
return(
"<div style='color:" + fg + "; " +
"background-color:" + bg + "; " +
"font-size:" + fontSize + "px'>\n" +
"<ul>\n");
}
71
function listEndTags() {
return("</ul></div>");
}
72
JSON Example Code: HTML
<fieldset>
<l
<legend>$.ajax:
d>$ j T
Treating
ti R
Response as JSON</l
JSON</legend>
d>
<input type="button" value="Show Nums"
id='nums-button'/>
<div id="nums-result3></div>
</fieldset>
73
• Notes
– Quotes around property names. Double, not single, quotes
– Client
Client-side
side code does not need wrap in parens and pass to
“eval”. JSON evaluation handled automatically by jQuery
– Types
• fg and bg: Strings
• fontSize: int
75 • numbers: Array of doubles
76
JSON Example Code: Auxiliary
Java Code
public class RandomUtils {
private static Random r = new Random();
77
78
© 2010 Marty Hall
Wrap-up
“Best” JavaScript
p Libraries
• General JS programming • Traditional Ajax support
– Leaders: Closure,
Closure Prototype – Tie
• Other programming (Java) • Server communication
– Leader (only): GWT – Leader: GWT
• DOM manipulation – 2nd tier:
ti DWR,
DWR JSON-RPC
JSON RPC
– Leader: jQuery • Usage in industry
• Others are copying jQuery
approach and closing gap. – Leader: jQuery
jQ
jQuery released
l d CSS – 2ndd tier:
i Ext-JS,
E JS D
Dojo,
j YUI
YUI,
matching library separately Prototype, Scriptaculous,
(http://sizzlejs.com) GWT
• Rich GUIs – Lowest: Google Closure
– Leaders: Ext-JS, YUI, Dojo • Support for extra-large
– 2nd tier: jQuery UI, GWT, projects
Google Closure
– Leaders: Closure,
Closure GWT
• Familiarity to JS
S developers nd
– 2 tier: Ext-JS, YUI, Dojo
– Lowest: GWT
80 – 2nd-lowest: Google Closure
Books and References
• jQuery in Action
– by Bear Bibeault, Yehuda Katz, and John Resig
Makes global variable blunder when showing normal Ajax
• jQuery 1.4 Reference Guide
– by Jonathan Chaffer and Karl Swedberg
• http://docs.jquery.com/
– Very complete
– Moderately well organized
– Moderate number of explicit examples
• jQuery UI 1.7
– Byy Dan Wellman
– Looks good, but jQuery UI is changing rapidly (current
version is 1.8), so the online docs are perhaps better
81
Summary
• Assigning event handlers programmatically
$(function() {
$("#some-id").click(someFunction);
});
Questions?