jQuery.ajax("hello.txt", // URL
{ // options
success: // callback
// describe an anonymous function
function(reply) {
var msg = "Got back " + reply;
alert(msg);
}
}
);
Can view request in Chrome Developer Tools (Win:F12, OSX:Cmd+Opt+I)
Other options we'll discuss:
data: to send with GET/POST
error, timeout: for error handling
Aside: Functional Programming
Functions can be inputs or outputs of functions
Old for JavaScript. Java added it last month!
Allows common idioms to be easily reused
// call 'action', a function,
// on every element of 'list'
forAll = function(list, action) {
for (var i=0; i<list.length; i++)
action(list[i]);
}
// alert twice
forAll(['x', 'y'], alert);
// log three times
forAll([12, 345, 6],
function(v) {console.log(v);});
// counter value, initially zero
counter = 0;
// clicking either button does this:
add = function(changeAmount) {
counter = counter + changeAmount;
// update number
counterLabel.innerHTML = counter;
// get line from server
jQuery.ajax("lyrics.php",
{ // use two options
data: {line: counter}, // to GET
success: function (reply) {
// update display!
resultLabel.innerText = reply;
}
});
};
Enhancement: Synch
How to avoid two changes at two times?
Let's fix it! Double-click on the HTML or JS above to edit it.
Enhancement: Spinner
If connection is slow, impatient user may click before line is
loaded, which can cause race conditions
$("button").each(function(){
this.disabled = true; // or false
});
$("#spinnerImg").show(); // or hide
<img id="spinnerImg" src="spinner.gif" hidden="true">
Enhancement: Prepopulating
User doesn't want to see "Line #: [---]" at start
Can we fill it out with line 1 automatically?
// ask jQuery to run function
// once page is loaded
jQuery(function() {
counter = 1;
add(0); //refresh, don't change value
});