this.fieldName// access field
this.fieldName = value; // modify field
this.methodName(parameters); // call method
all JavaScript code actually runs inside of an object
by default, code runs in the global window object (so this === window)
all global variables and functions you declare become part of window
the this keyword refers to the current object
Event handler binding
$(document).ready( function() {
$("textbox").on("mouseout", booyah);// bound to text box here$("submit").on("click", booyah);// bound to submit button here
});
function booyah() { // booyah knows what object it was called on$(this).value = "booyah";
}
event handlers attached unobtrusively are bound to the element
inside the handler, that DOM element becomes this (rather than the window)
inside the handler, the calling jQuery object becomes $(this)
function delayMsg() {
setTimeout(booyah, 5000);
document.getElementById("output").innerHTML = "Wait for it...";
}
function booyah() { // called when the timer goes off
document.getElementById("output").innerHTML = "BOOYAH!";
}
setInterval example
var timer = null;// stores ID of interval timer
function delayMsg2() {
if (timer == null) {
timer = setInterval(rudy, 1000);
} else {
clearInterval(timer);
timer = null;
}
}
function rudy() { // called each time the timer goes off
document.getElementById("output").innerHTML += " Rudy!";
}
Passing parameters to timers
function delayedMultiply() {
// 6 and 7 are passed to multiply when timer goes off
setTimeout(multiply, 2000, 6, 7);
}
function multiply(a, b) {
alert(a * b);
}
any parameters after the delay are eventually passed to the timer function
doesn't work in IE6; must create an intermediate function to pass the parameters
why not just write this?
setTimeout(multiply(6 * 7), 2000);
Common timer errors
many students mistakenly write () when passing the function
a set of options, as an array of key : value pairs in {} braces
(an anonymous JS object)
hides icky details from the raw XMLHttpRequest; works well in all browsers
$.ajax() configuration options
option
description
url
URL to submit the request to
data
data to send with the request, an associative array that will be converted to a query string
type
HTTP method of request, GET or POST
dataType
type of content to expect in the response (html, json, xml, etc.)
success
function to run if the request succeeds (response data is passed as a paramter)
error
function to run if the request fails (gets raw request and status code as paramters)
complete
function to run regardless if the request succeeds or fails
others: async, cache,
timeout, and many more...
$.ajax() example
$.ajax({
url: "post.php",
data: { id: 123 },
type: "GET",
dataType : "json",
success: function( json ) {
$( "<h1/>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
},
error: function( xhr, status ) {
alert( "Sorry, there was a problem!" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
attach handlers to the request's success, error, and/or complete events
Ajax Events
event
description
ajaxStart
triggered when an Ajax reqeust starts and there are no other Ajax requests running (global)
success
invoked if the request is successful (local)
error
invoked if there is an error in the request (success and error will never both be called) (local)
complete
called regardless of response state, always invoked (local)
ajaxStop
triggered when there are no more Ajax requests being processed (global)
Ajax Event Example
// Setting up a loading indicator using Ajax Events
$( "#loading_indicator" ).ajaxStart(function() {
$( this ).show();
}).ajaxStop(function() {
$( this ).hide();
});
XMLHttpRequest security restrictions
cannot be run from a web page stored on your hard drive
can only be run on a web page stored on a web server
can only fetch files from the same site that the page is on
http://www.foo.com/a/b/c.html can only connect to www.foo.com
JSONP provides a way around this - remote service returns data or code in a <script> tag, circumventing the same-origin olicy
Troubleshooting and debugging Ajax
Clear the browser cache
Watch the server logs (Rails development.log holds a lot of details)
Use Firebug, IE Developer Tools, Safari Web Inspector
Net tab shows each request, its parameters, response, any errors
expand a request with + and look at Response tab to see Ajax result
Make and test changes in very small increments.
Rails and Ajax
remote: true attribute in link_to or button_to
<%= button_to 'Add to Cart', line_items_path(product_id: product), remote: true %>
format.js in respond_to block to stop normal response
Write .js.erb file to handle response (i.e. HTML snippet, JSON)
escape_javascript
See Chapter 11 in the Rails text
<%= button_to 'Add to Cart', line_items_path(product_id: product), remote: true %>
12.3: XML
12.1: Ajax Concepts
12.2: Using XMLHttpRequest
12.3: XML
12.4: JSON
The bad way to store data
My note:
BEGIN
TO: Tove
FROM: Jani
SUBJECT: Reminder
MESSAGE (english):
Hey there,
Don't forget to call me this weekend!
END
we could send a file like this from the server to browser with Ajax
what's wrong with this approach?
What is XML?
XML: a "skeleton" for creating markup languages
you already know it!
syntax is identical to XHTML's:
<elementattribute="value">content</element>
languages written in XML specify:
names of tags in XHTML: h1, div, img, etc.
names of attributes in XHTML: id/class, src, href, etc.
rules about how they go together in XHTML: inline vs. block-level elements
used to present complex data in human-readable form
"self-describing data"
Anatomy of an XML file
<?xml version="1.0" encoding="UTF-8"?><!-- XML prolog --><note><!-- root element -->
<to>Tove</to>
<from>Jani</from><!-- element ("tag") -->
<subject>Reminder</subject> <!-- content of element -->
<message language="english"> <!-- attribute and its value -->
Don't forget me this weekend!
</message>
</note>
begins with an <?xml ... ?> header tag ("prolog")
has a single root element (in this case, note)
tag, attribute, and comment syntax is just like XHTML
Uses of XML
XML data comes from many sources on the web:
web servers store data as XML files
databases sometimes return query results as XML
web services use XML to communicate
XML is was the de facto universal format for exchange of data
natively supported by all modern browsers (and libraries to support it in old ones)
popularity steadily rising due to its simplicity and ease of use
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
in JavaScript, you can create a new object without creating a class
the object can have methods (function properties) that refer to itself as this
can refer to the fields with .fieldName or ["fieldName"] syntax
field names can optionally be put in quotes (e.g. weight above)
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!"
}
}