Вы находитесь на странице: 1из 24

IF300 5

JavaScript:
AJAX & XML
Seng Hansun
Computer Science Department – Universitas Multimedia Nusantara

Modified from Yustinus Widya Wiratama slides


Reviews
◉ Introduction to JavaScript
◉ ECMAScript
◉ Variable
◉ Function
◉ Events
◉ Document Object Model
◉ JSON

Modified from Yustinus Widya Wiratama slides


Course Outline
◉ Intro to AJAX
◉ Intro to XML
◉ HTTP GET via AJAX (JSON & XML)
◉ JavaScript Built-in Functions (String, Math, Date)

Modified from Yustinus Widya Wiratama slides


Asynchronous JavaScript and XML
◉ Asynchronous JavaScript and XML (AJAX) is a technique
for creating fast and dynamic web pages.
◉ It allows web pages to be updated asynchronously by
exchanging small amounts of data with the server behind
the scenes which makes it possible to update parts of a
web page, without reloading the whole page.
◉ A classic web page (without AJAX), must reload the entire
page if you want to change the content.

Source: http://www.w3schools.com/ajax/default.asp
Modified from Yustinus Widya Wiratama slides
How AJAX Works
An event occurs... 1. Process HttpRequest
1. Create an object of 2. Create a response and
Internet
XMLHttpRequest send data back to the
2. Send HttpRequest browser

1. Process the returned


data using JavaScript Internet
2. Update page content

AJAX is based on internet standards and uses a combination of:


◉ XMLHttpRequest object to retrieve data from a web server
◉ JavaScript/DOM to display or use the data
Modified from Yustinus Widya Wiratama slides
AJAX – XMLHttpRequest Object
◉ XMLHttpRequest object is the most important things
in AJAX.
◉ XMLHttpRequest object is used to exchange data
with a server behind the scenes.
◉ XMLHttpRequest create syntax:
variable = new XMLHttpRequest();
◉ Create XMLHttpRequest object example:
var xhttp = new XMLHttpRequest();

Modified from Yustinus Widya Wiratama slides


Send a Request to a Server
◉ To send a request to a server, utilize the open() and
send() methods of the XMLHttpRequest object.

Modified from Yustinus Widya Wiratama slides


AJAX Server Response
To receive the response from a server, utilize the responseText
or responseXML property of the XMLHttpRequest object.
◉ Use responseXML property if the response from the server
is in XML format.
◉ Use the responseText property if the response from the
server is not in XML format.
◉ The responseText property returns the response as a string
then you can use it directly.
document.getElementById("demo").innerHTML
= xhttp.responseText;

Modified from Yustinus Widya Wiratama slides


AJAX Events
◉ When a request to a server is sent, we can perform
some actions based on the response.
◉ The onreadystatechange event is triggered every
time the readyState changes.
◉ In the onreadystatechange event, we can specify
what will happen when the server response is ready
to be processed.
◉ The readyState property holds the status of the
XMLHttpRequest.
Modified from Yustinus Widya Wiratama slides
AJAX Events
Three important properties of the XMLHttpRequest object:
Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically
each time the readyState property changes
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found

Modified from Yustinus Widya Wiratama slides


AJAX Server JSON Response Example
function loadData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var text = this.responseText; var data = JSON.parse(text);
document.getElementById("name").innerHTML =
data.results[0].name.last;
document.getElementById("gender").innerHTML =
data.results[0].gender;
document.getElementById("email").innerHTML =
data.results[0].email;
document.getElementById("picture").src =
data.results[0].picture.medium;
}
};
xhttp.open("GET", "https://randomuser.me/api/", true);
xhttp.send();
}
Modified from Yustinus Widya Wiratama slides
Extensible Markup Language
◉ eXtensible Markup Language (XML) was designed to store and
transport data, and to be both human and machine readable.
◉ XML document does not DO anything. XML is just information
wrapped in tags. Someone must write a piece of software to send,
receive, store, or display it.
◉ XML vs. HTML :
• XML was designed to carry data - with focus on what data is
• HTML was designed to display data - with focus on how data looks
• XML tags are not predefined like HTML tags are
◉ Most XML applications will work as expected even if new data is
added (or removed).
◉ XML became a W3C Recommendation on February 10, 1998.
Modified from Yustinus Widya Wiratama slides
XML Syntax Rules
◉ XML Prolog
The XML Prolog is optional, if it exists, it must come first in the
document.
◉ XML Document must have a root element.
Must contain one root element that is the parent of all other
elements.
◉ All XML elements must have a closing tag
◉ XML Tags are case sensitive
◉ XML Elements must be properly nested
◉ XML Attribute Values must be quoted
◉ Entity References
Some characters have a special meaning in XML
Modified from Yustinus Widya Wiratama slides
XML Example
<library>
<book id="101">
<title>Mobile HTML5</title>
<author>Estelle Weyl</author>
<publisher>O&apos;Reilly Media</publisher>
<year>2013</year>
</book>
<book id="102">
<title>Design for New Media</title>
<author>Lon Barfield</author>
<year>2004</year>
</book>
</library>

Modified from Yustinus Widya Wiratama slides


XML Elements
XML element is everything from and including the element's
start tag, to and including the element's end tag.
◉ XML Elements are extensible.
XML elements can be extended to carry more information
without breaking applications.
◉ Inside XML Elements
• text
• attributes
• other elements
• or a mix of the above
Modified from Yustinus Widya Wiratama slides
XML Elements
◉ Empty XML Elements
An element with no content is said to be empty.
<element></element>
<element />
◉ XML Naming Rules
• Element names are case-sensitive
• Element names must start with a letter or underscore
• Element names cannot start with the letters xml (or XML, or Xml, etc.)
• Element names can contain letters, digits, hyphens, underscores, and
periods
• Element names cannot contain spaces
Modified from Yustinus Widya Wiratama slides
XML Example

http://ww
w.w3scho
ols.com/x
ml/xml_tr
ee.asp

Modified from Yustinus Widya Wiratama slides


XML Example

http://www.w3schools.com/xml/xml_tree.asp

Modified from Yustinus Widya Wiratama slides


AJAX Server XML Response Example
function loadData() {
var xmlDoc, artists, txt = "";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
xmlDoc = this.responseXML;
artists = xmlDoc.getElementsByTagName("ARTIST");
for (var i = 0; i < artists.length; i++) {
txt = txt + artists[i].childNodes[0].nodeValue +
"<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
Modified from Yustinus Widya Wiratama slides
}
String Built-in Functions
Method Description
charAt() Returns the character at the specified index (position)
endsWith() Checks whether a string ends with specified string/characters
includes() Checks whether a string contains the specified string/characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
match() Searches a string for a match against a regular expression, and returns the
matches
replace() Searches a string for a specified value, or a regular expression, and returns a
new string where the specified values are replaced
search() Searches a string for a specified value, or regular expression, and returns the
position of the match
Modified from Yustinus Widya Wiratama slides
String Built-in Functions
Method Description
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
Extracts the characters from a string, beginning at a specified start position,
substr()
and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object

Modified from Yustinus Widya Wiratama slides


Math Built-in Functions
The Math object allows you to perform mathematical tasks.
Math methods can be called by using Math as an object, without creating it.
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
x
exp(x) Returns the value of E
floor(x) Returns x, rounded downwards to the
Modified fromnearest integer
Yustinus Widya Wiratama slides
Date Built-in Functions
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1 1970, and
a specified date

Modified from Yustinus Widya Wiratama slides


References
◉ W3Schools. AJAX Tutorial,
http://www.w3schools.com/ajax/default.asp
◉ W3Schools. XML Tutorial,
http://www.w3schools.com/xml/default.asp
◉ W3Schools. JavaScript Reference,
http://www.w3schools.com/jsref/default.asp

Modified from Yustinus Widya Wiratama slides