Javascript, Jquery and Ajax: Lab. Bases de Dados E Aplicações Web Mieic, Feup 2014/15 Sérgio Nunes
Javascript, Jquery and Ajax: Lab. Bases de Dados E Aplicações Web Mieic, Feup 2014/15 Sérgio Nunes
Srgio Nunes
Client-Side Technology
HTML > content & structure.
Context
Client-side scripting language that runs on web browsers.
Interpreted and object-oriented language.
Unrelated to Java.
Use Cases
Modify appearance of a web page.
JavaScript Code
function do() {
var foo = "Hello World!";
var bar1 = 1;
var bar2 = 2;
var text = foo + bar1 + bar2;
console.log(text);
}
Comments in JavaScript
JavaScript supports both single-line comments
and multi-line comments.
function do() {
// This is a single line comment.
alert("Hello World!");
/* This is a
multi-line
comment.
*/
}
8
JavaScript Intro
Using JavaScript
JavaScript can be included in a web document using three approaches:
10
Embedded JavaScript
JavaScript can be attached to HTML elements using event handlers
such as onclick, onmousedown, onmouseup, etc.
11
Inline JavaScript
JavaScript code can be embedded within the HTML document
using the script element.
<h1>Page Title</h1>
<script type="text/javascript">
document.write("Print this text!");
</script>
<p>Yada, yada, yada!</p>
12
External JavaScript
JavaScript may be defined in an independent file and then attached to
multiple HTML documents.
13
Primitive Types
Numbers: 23, 2.3, .23.
Undefined: undefined.
Null: null.
Numbers, strings and booleans are object-like in that they have methods.
14
Variables
JavaScript is a dynamically typed language. No need to specify the
data type in variable declaration. Data types are converted
automatically as needed during execution.
15
Expressions
An expression is any valid set of literals, variables, operators, and expressions
that evaluate to a single value.
16
Strings
Strings can be joined together using the concatenation operator (+).
17
Assignment Operators
An assignment operator assigns a value to its left operand based on
the value of its right operator.
Shorthand Operator
Meaning
x += y
x = x + y
x -= y
x = x - y
x *= y
x = x * y
x /= y
x = x / y
x %= y
x = x % y
x ^= y
x = x ^y
18
Comparison Operators
A comparison operator compares its operand and returns a logical
value based on whether the comparison is true.
Operator
Description
Equal (==)
Returns true if the operands are equal and of the same type.
Returns true if the operands are not equal and/or not of the same type.
Returns true if the left operand is greater than the right operand.
Returns true if the left operand is lower than the right operand.
19
Arithmetic Operators
Arithmetic operators take numerical values as their operands and
return a single numerical value.
Operator
Description
Modulus (%)
Increment (++)
Decrement (--)
Logical Operators
Logical operators are typically used with Boolean values.
Operator Description
&&
||
21
Objects
JavaScript objects are simply collections of name-value pairs.
var obj1 = new Object();
// or
var obj2 = {};
obj.name = "John";
obj.surname = "Doe";
obj.age = 40;
// or
obj["name"] = "John";
obj["surname"] = "Doe";
obj["age"] = 40;
22
Arrays
In JavaScript arrays are a special type of objects.
etc.
cars[0] = "Ford";
cars[1] = "Opel";
cars[2] = "BMW";
}
23
Statements
24
Block Statements
Block statements are used to group statements together. The block is
delimited using curly brackets.
{
statement_1;
statement_2;
...
statement_n;
}
25
Conditional Statements
A conditional statement is a set of commands that executes if a specified
condition is true.
if..else statement
switch statement
if (condition) {
switch (expression) {
case label1:
statements
statements
} [else {
break;
statements
case label2:
}]
statements
break;
default:
statements
}
26
Loop Statements
Loop statements executes repeatedly until a specified condition is met.
do while
var i = 0;
while
var n = 0;
while (n < 3) {
n++;
do {
i += 1;
document.write(i);
} while (i < 5);
document.write(n);
}
27
The continue statement can be used to restart a for, do...while, while, or label
statement. It can be used with or without a label.
28
The with statement establishes the default object for a set of statements.
var cars = ["Ford", "Opel", "BMW"];
for (x in cars) {
document.write(cars[x] + " ");
// Ford Opel BMW
}
var a = 0;
with (Math) {
a = PI + cos(PI) * sin(PI);
}
29
Functions
Functions are a core element in JavaScript.
Functions are defined using the function keyword followed by the name of the
function, the list of arguments separated by commas and enclosed in
parentheses, and the function statements enclosed in curly braces.
alert((function (number) {
return number * number;
})(5));
Standard function
Anonymous function
30
Exception Handling
With JavaScript is possible to throw exceptions with the throw command and
handle them using the try...catch command. A finally block statement can
exist to be executed after the try...catch block.
throw "Error2";
try {
throw 42;
throw true;
functionXYZ(); }
catch (e if e == "InvalidNameException") {
openXYZ();
try {
// try something
catch (e if e == "InvalidIdException") {
} catch (e) {
// handle problems
} finally {
catch (e) {
closeXYZ();
}
// or else...
}
31
jQuery Overview
32
jQuery
jQuery is a cross-browser JavaScript library developed by John Resig (2006).
33
Support extensions.
34
jQuery Setup
The jQuery library needs to be loaded to be used in a HTML document.
36
37
jQuery(document.body).css('background', 'green');
$("ul.menu").slideUp();
$('div.foo').click(function() {
$('p.bar img').hide();
});
38
Selectors
The jQuery library supports most CSS selectors.
$(":radio:checked");
$("a[href^=mailto:]");
$("td:contains(A)");
$(":button");
$("a[href=.pdf]");
$("a:not(.foo)");
form selectors
atributte selectors
custom selectors
$("a.foo").filter(".bar").children();
$("p.bar").children();
$("#bar").filter("p").first();
transversing
39
Manipulation
The jQuery .css() method can be used to get or set styles. There are several
shortcuts, particularly for dimension properties, e.g. .with(), .height().
The attributes of any element may be get or set using the .attr() method.
The content of elements can be edited using the methods .html() or .text().
$("p").css("color", "red");
$("h1").addClass("active");
$("a.bar").attr("href");
Events
Tasks can be performed when the page loads or in response to some event.
$("h1").click(function() {
// do something
// do something
}
Event Propagation
When an event occurs on a page, an entire hierarchy of DOM elements gets a
chance to handle the event.
The .stopPropagation() method halts the propagation process for the event.
The .preventDefault() method will stop standard actions like following links or
submitting forms on Enter.
$("p.foo").click(function(event) {
$("a").click(function(event) {
// do something
event.preventDefault();
event.stopPropagation();
// do something
43
Effects
jQuery can be used to add simple visual eects and animations.
The .hide() and .show() methods are frequently used for basic visual eects.
Both methods accept a speed value that controls the duration of the eect.
$("#bar").hide;
$("#bar").show("fast");
custom animations
Several visual eects where separated form the core and organized in the
jQuery UI library http://jqueryui.com/ (e.g. calendar widgets, sliders, etc).
44
Autocomplete http://plugins.jquery.com/project/autocompletex
Validation http://plugins.jquery.com/project/validate
Tablesorter http://tablesorter.com/
FancyBox http://fancy.klade.lv/
Thickbox http://jquery.com/demo/thickbox/
Flot http://code.google.com/p/flot/
45
jQuery Documentation
Selectors
http://api.jquery.com/category/selectors/
Manipulation
http://api.jquery.com/category/manipulation
Eects
http://api.jquery.com/category/eects
Events
http://api.jquery.com/category/events
Plug-ins
http://plugins.jquery.com/
46
Ajax
47
What is Ajax?
Server calls from web pages using JavaScript
call
HTTP
data
48
Motivation
The traditional request-response cycle in web applications is synchronous.
Principal motivation for Ajax use is the improved user experience in web
applications.
49
Brief History
In 1999 Microsoft introduced the XMLHTTP feature in IE 5.
First web apps incorporating background HTTP requests date back to 2000.
Wider visibility and adoption happened after GMail (2004) and Google Maps
(2005).
50
Ajax
Ajax stands for Asynchronous JavaScript and XML.
Many libraries and toolkits are available to abstract low-level details (e.g.
jQuery, Prototype, Dojo, etc).
Typical use cases: form validation (e.g. mandatory fields), simple interactions
(e.g. likes), input field suggestions.
51
Server
request
processing
waiting
html
html
request
processing
waiting
html
html
52
Server
background
request
processing
xml data
html
background
request
processing
xml data
53
XMLHttpRequest object
JavaScript object that can handle communication between clients and
servers. The XMLHttpRequest object is created by the client.
Browser
JavaScript
2. HTTP request
XMLHttpRequest
3. HTTP response
1. Event
Generated
Server
4. Update
Document
Web Page
54
XMLHttpRequest Example
var xmlhttp = new XMLHttpRequest();
function handleRequest() {
if (xmlhttp.readyState == 4) {
// ok ...
} else { // not ok ... }
}
55
JSON
JSON stands for JavaScript Object Notation.
<person>
<firstName>John</firstName>
<lastName>Smith</lastName>
<age>25</age>
</person>
XML
{
"firstName": "John",
"lastName": "Smith",
"age": 25
}
JSON
56
JSON Examples
{
"firstName": "John"
"firstName": "John",
"lastName": "Smith"
"firstName": "John",
"tags": ["a", "b", 1]
"firstName": "John",
"address": {
"street": "Sesame",
"city": "NYC"
}
}
{
}
{
}
{
57
$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
59
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
61
Parsing JSON
jQuery.parseJSON( json )
Takes a well-formed JSON string and returns the
resulting JavaScript object.
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
62
Cross-domain Ajax
The same-origin policy prevents scripts from one domain to access or
manipulate properties or documents from another domain.
The HTML script element, not limited by the same-origin policy, is used to
load external data and call a local function defined in the callback parameter.
63
<script type="text/javascript"
src="http://example.com/api/foo.json?callback=processData">
</script>
1. Make call within the script element, include the local function name for the callback.
processData({"id":123, "name":"foo"})
2. Server send data padded with function name.
64
Reverse AJAX
65
Reverse Ajax
Ajax calls are initiated by the client.
66
Polling
Make periodic requests to the server to check for new data.
The smaller the interval between request the more up to date the data is.
Comet
Requests are initiated by the clients and kept alive for long periods, until a
time-out occurs or a response is sent.
Web Sockets
Web Sockets is an API that enables bidirectional communications between
the web browser and the web server. No polling is needed to get messages
from the server.
Ajax Drawbacks
Pages dynamically created using Ajax requests are not available in the
browser's history.
Dynamically created web pages are inaccessible to web crawlers, given that
they require JavaScript execution.
71
72
Popular Frameworks
Backbone.js
http://backbonejs.org/
Knockout.js
http://knockoutjs.com/
AngularJS
http://angularjs.org/
Ember.js
http://emberjs.com/
References
Learning jQuery 1.3
Jonathan Chaer, Karl Swedberg. Packt (2009)
jQuery Cookbook
jQuery Community Experts, O'Reilly (2010)