AJAX, XML y JSON


Comunicación síncrona web

synchronous communication

Aplicaciones Web y Ajax

Ajax bleach

Comunicación asíncrona web

synchronous communication

XMLHttpRequest

Petición típica Ajax

request
  1. user clicks, invoking an event handler
  2. handler's code creates an XMLHttpRequest object
  3. XMLHttpRequest object requests page from server
  4. server retrieves appropriate data, sends it back
  5. XMLHttpRequest fires an event when data arrives
    • this is often called a callback
    • you can attach a handler function to this event
  6. your callback event handler processes the data and displays it

Ajax - Asynchronous JavaScript and XML

Uso de Javascript para obtener más contenido desde el servidor sin navegar a otra página

let xhr = new XMLHttpRequest();
xhr.open(method, url, [async/sync]);
xhr.onload = function() { /* handle success */ };
xhr.onerror = function() { /* handle failure */ };
xhr.send();
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt");
xhr.onload = function() { alert(this.responseText); };
xhr.onerror = function() { alert("ERROR!"); };
xhr.send();

Como se ha mencionado antes no se aconseja usar el método de llamada AJAX de XML sobre HTML

Ejemplo texto

Ejemplo xml

Ejemplo json

jQuery's ajax method

$.ajax({
	"url": "http://foo.com",
	"option" : "value",
	"option" : "value",
	...
	"option" : "value"
});

$.ajax() options

option description
url The URL to make a request from
type whether to use POST or GET
data an object literal filled with query parameters and their values
dataType The type of data you are expecting to recieve, one of: "text", "html", "json", "xml"
timeout an amount of time in seconds to wait for the server before giving up
success event: called when the request finishes successfully
error event: called when the request fails
complete event: called when the request finishes successfully or erroneously

jQuery AJAX example

$.ajax({
	"url": "foo/bar/mydata.txt",
	"type": "GET",
	"success": myAjaxSuccessFunction,
	"error": ajaxFailure
});
function myAjaxSuccessFunction(data) {
	// do something with the data
}
function ajaxFailure(xhr, status, exception) {
	console.log(xhr, status, exception);
}

AJAX data parameter

The data passed to your success handler will be in whatever format you specified in the dataType option

Handling Ajax errors

$.ajax(
	"url": "http://foo.com",
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});
...
function ajaxFailure(xhr, status, exception) {
	console.log(xhr, status, exception);
}

Better jQuery AJAX

Rather than specify all of the options in an object literal...

$.ajax({
	"url": "http://foo.com",
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

one can pass the URL as the first parameter and the rest as an object literal.

$.ajax("http://foo.com", {
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

Why? It makes it even easier to see what this AJAX request is doing.

Debugging AJAX code

Chrome Ajax

More about $.get() and $.post()

function description
$.ajax() A general function for making AJAX requests, other AJAX functions rely on this
$.get() makes a GET request via AJAX
$.post() makes a POST request via AJAX

Why bother making the distinction if it all boils down to a call to $.ajax() under the hood

XMLHttpRequest security restrictions

Ajax security error

XML

Storing structured data in arbitrary text formats (bad)

My note:
BEGIN
	TO: Alice Smith (alice@example.com)
	FROM: Robert Jones (roberto@example.com)
	SUBJECT: Tomorrow's "Birthday Bash" event!
	MESSAGE (english):
		Hey Bob,
		Don't forget to call me this weekend!
	PRIVATE: true
END

XML: A better way of storing data

<?xml version="1.0" encoding="UTF-8"?>
<note private="true">
	<to>Alice Smith (alice@example.com)</to>
	<from>Robert Jones (roberto@example.com)</from>
	<subject>Tomorrow's "Birthday Bash" event!</subject>
	<message language="english">
		Hey Bob, Don't forget to call me this weekend!
	</message>
</note>

What is XML?

Anatomy of an XML file

<?xml version="1.0" encoding="UTF-8"?>      <!-- XML prolog -->
<note private="true">                       <!-- root element -->
	<to>Alice Smith (alice@example.com)</to>
	<from>Robert Jones (roberto@example.com)</from>
	<subject>Tomorrow's "Birthday Bash" event!</subject>
	<message language="english">
		Hey Bob, Don't forget to call me this weekend!
	</message>
</note>

Uses of XML

What tags are legal in XML?

<measure number="1">
	<attributes>
		<divisions>1</divisions>
		<key><fifths>0</fifths></key>
		<time><beats>4</beats></time>
		<clef>
			<sign>G</sign><line>2</line>
		</clef>
	</attributes>
	<note>
		<pitch>
			<step>C</step>
			<octave>4</octave>
		</pitch>
		<duration>4</duration>
		<type>whole</type>
	</note>
</measure>

XML and Ajax

Ajax bleach

Fetching XML using Ajax (template)

node tree
$.get("foo.xml")
	.done(functionName);

function functionName(xmlDom) {
	// do stuff with the xmlDom just like you would with the HTML dom
}

XML DOM tree structure

node tree
<?xml version="1.0" encoding="UTF-8"?>
<categories>
  <category>children</category>
  <category>computers</category>
  ...
</categories>

Interacting with XML DOM nodes manually

node tree

To get a list of all nodes that use a given element:

var elms = node.getElementsByTagName("tag");

To get the text inside of a node:

var text = node.firstChild.nodeValue;

To get an attribute's value from a node:

var attrValue = node.getAttribute("name");

Full list of XML DOM properties

XML DOM and jQuery

You use the same jQuery functions to interact with the XML DOM, with one minor tweak:

Ajax XML DOM example

<?xml version="1.0" encoding="UTF-8"?>
<employees>
	<lawyer money="99999.00" />
	<janitor name="Ed"> <vacuum model="Hoover" /> </janitor>
	<janitor name="Bill">no vacuum, too poor</janitor>
</employees>
// how much money does the lawyer make?
$(xmlDom).find("lawyer").attr("money");	// "99999.00"

// array of 2 janitors
var janitors = $(xmlDom).find("janitor");
janitors.find("vacuum").attr("model");		// "Hoover"
janitors.last().text();										// "no vacuum, too poor"

Larger XML file example

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
	<book category="cooking">
		<title lang="en">Everyday Italian</title>
		<author>Giada De Laurentiis</author>
		<year>2005</year><price>30.00</price>
	</book>
	<book category="computers">
		<title lang="en">XQuery Kick Start</title>
		<author>James McGovern</author>
		<year>2003</year><price>49.99</price>
	</book>
	<book category="children">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year><price>29.99</price>
	</book>
	<book category="computers">
		<title lang="en">Learning XML</title>
		<author>Erik T. Ray</author>
		<year>2003</year><price>39.95</price>
	</book>
</bookstore>

Navigating node tree example

// make a paragraph for each book about computers
$(xmlDom).find("book[category='computer']").each(function(idx, e) {
	// extract data from XML
	var title = $(e).find("title").text();
	var author = $(e).find("author").text();

	// make an HTML <p> tag containing data from XML
	$("<p>")
		.text(title + ", by " + author)
		.appendTo($(document.body));
});

JSON

JavaScript Object Notation (JSON)

json
json

JavaScript Object Notation (JSON): Data format that represents data as a set of JavaScript objects

Recall: JavaScript object syntax

var person = {
	"name": "Philip J. Fry",                           // string
	"age": 23,                                         // number
	"weight": 172.5,                                 // number
	"friends": ["Farnsworth", "Hermes", "Zoidberg"],   // array
	"getBeloved": function() { return this.name + " loves Leela"; }
};
alert(person.age);                                 // 23
alert(person["weight"]);                           // 172.5
alert(person.friends[2]));                         // Zoidberg
alert(person.getBeloved());                        // Philip J. Fry loves Leela

An example of XML data

<?xml version="1.0" encoding="UTF-8"?>
<note private="true">
	<from>Alice Smith (alice@example.com)</from>
	<to>Robert Jones (roberto@example.com)</to>
	<to>Charles Dodd (cdodd@example.com)</to>
	<subject>Tomorrow's "Birthday Bash" event!</subject>
	<message language="english">
		Hey guys, don't forget to call me this weekend!
	</message>
</note>

The equivalant JSON data

{
	"private": "true",
	"from": "Alice Smith (alice@example.com)",
	"to": [
		"Robert Jones (roberto@example.com)",
		"Charles Dodd (cdodd@example.com)"
	],
	"subject": "Tomorrow's \"Birthday Bash\" event!",
	"message": {
		"language": "english",
		"text": "Hey guys, don't forget to call me this weekend!"
	}
}

Browser JSON methods

method description
JSON.parse(string) converts the given string of JSON data into an equivalent JavaScript object and returns it
JSON.stringify(object) converts the given object into a string of JSON data (the opposite of JSON.parse)

JSON expressions exercise

var data = JSON.parse(jsonString);
{
	"window": {
		"title": "Sample Widget",
		"width": 500,
		"height": 500
	},
	"image": {
		"src": "images/logo.png",
		"coords": [250, 150, 350, 400],
		"alignment": "center"
	},
	"messages": [
		{"text": "Save", "offset": [10, 30]}
		{"text": "Help", "offset": [ 0, 50]},
		{"text": "Quit", "offset": [30, 10]},
	],
	"debug": "true"
}

Given the JSON data at right, what expressions would produce:

var title = data.window.title;
var coord = data.image.coords[2];
var len = data.messages.length;
var y = data.messages[len - 1].offset[1];

JSON and AJAX (AJAJ?...)

$.get("foo.json")
	.done(functionName);

function functionName(jsonObj) {
	// do stuff with the jsonObj
}

Referencias