Welcome!
Everything is fine.
Ajax¶
Today doesn't have a lot of code but has some important concepts.
Plan¶
- Announcements
- Recap Ajax
- Answer your questions
- Breakout
Announcements¶
- None for now
Ajax Motivation¶
Ajax is incredibly important in modern web development. Remember this quote from the reading:
It can be successfully argued that no single technology shift has transformed the landscape of the web more than Ajax. The ability to make asynchronous requests back to the server without the need to reload entire pages has enabled a whole new set of user-interaction paradigms and made DOM-scripted applications possible.
Bear Bibeault & Yehuda Katz
jQuery in Action, 2nd edition
However, using Ajax requires a very different way of thinking and coding, by using callbacks instead of return values.
(I've even heard people say we should not teach return values in classes like CS 111; we should start people with callbacks.)
It also means having to think about asynchronous events.
This is very hard, but it's critically important in modern web development, both front-end and back-end.
Ajax Concepts¶
- JS code running in the browser sends a request to the server.
- The sending JS code also designates a function that receives the response.
- The server, eventually, hopefully, responds to the request.
- The receiver code is invoked with the response and does whatever it wants, usually updating the page.
Here's the picture from the reading:
The green arrow from browser to server shows the request being sent. The blue arrow from server to browser shows the response being sent.
You can ignore the Python code in the server (back-end) box, but if you take CS 304, you'll learn how to implement that.
LocalStorage vs Ajax¶
With localStorage that we learned last time, we can save persistent data, but it's local. No sharing across devices:
But with Ajax, we can exchange data with a server on the internet, and so we can share data across devices:
Ajax is, essentially, the blue two-way arrows in that diagram.
Additional Notes¶
A few more notes, building on our discussion of localStorage from last time:
- Initializing is a little trickier, because we don't necessarily know when there's no prior data. Need suitable defaults.
- Data is always stored as strings
- Can use JSON to parse and stringify data structures, though some things (like dates, functions and objects with methods) don't inter-convert easily.
jQuery Reference¶
There are essentially three jQuery methods that make Ajax easier: two shortcuts and a general but low-level method:
- $.get(url, callback) gets some data from the server
- $.post(url, data, callback) sends (posts) some data to the server
- $.ajax(url, settings) for less common requests, like "delete"
There's a (relatively) new fetch
API in browers that supplants these
jQuery methods. A future version of this course may drop jQuery in
favor of these native APIs, but I still like jQuery.
There's also a non-callback way to use Ajax, using Promises and
async/await
but we're not going to do that; we can understand
callbacks.
Essential Uses¶
Open up the datastore-module in another window, so you can see them side-by-side.
We only use Ajax in a single class in a single module in all of CoffeRun:
class RemoteDataStore {
// instance variables
serverUrl = null;
constructor (url) {
if (!url) {
throw new Error('No remote URL supplied');
}
this.serverUrl = url;
}
add (key, val) {
$.post(this.serverUrl, val, function (serverResponse) {
console.log(serverResponse);
});
}
getAll (callback) {
$.get(this.serverUrl, function (serverResponse) {
console.log('getAll serverResponse: ',serverResponse);
callback(serverResponse);
});
}
get (key, callback) {
$.get(this.serverUrl + '/' + key, function (serverResponse) {
console.log('get '+key+' serverResponse: ',serverResponse);
callback(serverResponse);
});
}
remove (key) {
$.ajax(this.serverUrl + '/' + key, {
type: 'DELETE'
});
}
Observations:
- Change to the
constructor
to add the URL of the cloud server (Heroku) - No change to the
add
method, since the original didn't return a value. - Change the
get
andgetAll
methods, since the original returned a value. Instead, we now require the caller to provide a callback function.
CoffeeRun Demo¶
I'll demo coffeerun with cloud storage
Your Questions¶
I'll answer your questions
Movie Rating Demo¶
Here's how we use Ajax in CS 304 for movie-ratings
I'll demo using two browsers, but you're welcome to play along as well.
- "login" by giving a smallish number, say any number less than 100
- see a list of all the movies in the WMDB (Wellesley Movie Database)
- you can rate one or more the old-fashioned, non-Ajax way
- you can turn on progressive enhancement (fancy JS)
- rate one or more the slick Ajax way
The Ajax way has some advantages:
- Nicer interface
- much faster network interaction, because
- less data is sent from server
- page just needs to be updated, not rendered from scratch
Here's a screenshot I made earlier:
I'll demo the developer tools network tab to show this.
Additional notes: the Ajax version
- Uses delegated event handlers, like you are doing in the Quizzes assignment right now
- Uses forms with radio buttons, like you are doing now
- Use jQuery methods to make selections bold and to update the page with the new rating, which you've done before
There's nothing in this page you don't know how to do!
Heroku Server¶
Coffeerun used to have a Heroku server, but that seems to have been shut down. So I built one for us to use.
CoffeeRun Remote Database API¶
The database API has to change because the methods like .get(id)
and .getAll()
can no longer return values, but instead have to be
written to take a callback function. So,
not this:
var customerIdArray = Object.keys(this.db.getAll());
// code using customerIdArray ...
but this:
this.db.getAll(function (obj) {
var customerIdArray = Object.keys(obj);
// code using customerIdArray ...
});
That changes the code in the truck
module, as covered in the reading.
CoffeeRun with Ajax¶
I'll demo coffeerun with cloud storage
I can't demo the Heroku server because it's dead.
We'll be able to use the CS 304 server in our assignments and projects. I can set you up with a username/password in just minutes.
Timing¶
Which message is printed first?
$.get('characters.json',function (data) {
console.log('Done. Got '+data);
});
console.log('Finally done.');
Try it!
Breakouts¶
You can
- work on Jelly Blobs
- play with the CoffeeRun app
Summary¶
Ajax and callback-based coding is incredibly important
- interact with cloud-based services
- seamless user interactions
You can use this in your final project in CS 204