Gots N' Needs Notecards

Got picture

On one side of the notecard write what you feel like you "got" so from doing Homework Assignment 3 and CP 3.

Need picture

On the other side of the notecard, write something you feel you still need to understand, or that would help you understand this material.

CSE 154

Lecture 12: AJAX, Fetch, and Promises

On tap today

Quick discussion of HW 4

Quick demo of the ducky store

Intro to AJAX, promises, and fetch

web application:
a dynamic web site that feels like a desktop application
AJAX:
a specific style of using JS to call out to the server for more information
Promise:
a JS object that is useful for dealing with uncertainty in your program

Web Applications

All of the pages that we've made up until now have content, style, and behavior.

Web applications are webpages that pull in additional data and information as the user progresses through them, making it feel similar to a desktop application.

Some motivations for making web pages into web applications:

  • Better user experience
  • Less data sent across the wire
  • Leads to good software architecture:
    • Client handles display, server serves up data

Synchronous requests:

synchronous request diagram

Why synchronized requests are problematic

Your code waits for the request to completely finish before proceeding. Might be easier for you to program, but the user's entire browser LOCKS UP until the download is completed, which is a terrible user experience (especially if the page is very large or slow to transfer)

Asynchronous requests:

asynchronous request diagram

Ajax

Using Javascript to pull in more content from the server without navigating the page to a new url


let xhr = new XMLHttpRequest();
xhr.open(method, url, [async/sync]);
xhr.onload = function() { /* handle success */ };
xhr.onerror = function() { /* handle failure */ };
xhr.send();
          

JS (template)


let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt");
xhr.onload = function() { alert(this.responseText); };
xhr.onerror = function() { alert("ERROR!"); };
xhr.send();
          

JS (example)

Although we are showing you this, it is for context only, we will not be using the "XML over HTTP" method of AJAX calls.

Ajax
Asynchronous JavaScript and XML

The XMLHttpRequest object can be used synchronously or asynchronously.

So this functionality could be called S/Ajax or A/Sjax. But Ajax has a nice ring to it.

It's better to use async so that the page doesn't block waiting for the page to come back. We have no use cases in this class for using Ajax synchronously.

Ajax
Asynchronous JavaScript and XML

the XMLHttpRequest object can be used to fetch anything that you can fetch with your browser.

This includes XML (like in the name), but also JSON, HTML, plain text, media files.

So it could be called Ajaj or Ajah or Ajat. But Ajax has a nice ring to it.

Debugging Ajax

Use the inspector, watch the network tab to see the requests that go out.

debugging ajax image

In summary: Using Ajax

  • using JS to download data (or other stuff) from the server in the background
  • allows dynamically updating a page without making the user wait
  • JSON is now more common than XML, but they are both just ways to store data
  • not a programming language; a particular way of using JavaScript
  • avoids the "click-wait-refresh" pattern
  • examples: UW's CSE 14x Diff Tool, Practice-It; Amazon product pages, most auto-complete search features
ajax diagram

Promises

Real world promises

Promises have three states:

  • Pending
  • Fulfilled
  • Rejected

Example: “I promise to post homework 4”
Pending: Not yet posted
Fulfilled: Homework 4 posted
Rejected: Wrong homework posted, or not posted in time

JavaScript Promises

promise
A JS object that executes some code that has an uncertain outcome

Promises have three states:

  • Pending
  • Fulfilled
  • Rejected

            let promise = new Promise( function( resolve, reject ) {
                // do something uncertain (like make an ajax call)

                if ( success ) {
                    resolve();     // Fulfilled
                } else {
                    reject();      // Rejected
                }
            });
        

JS (template)

Wrapping a Promise in a fetch call

We will be using promises to fetch information from a server, which is an uncertain task

Our Promise has been wrapped in a fetch call that has much the same structure

We give you "boilerplate" starting code because you will use this frequently

Ajax fetch Code Skeleton

// include this code,
// based on: https://developers.google.com/web/updates/2015/03/introduction-to-fetch
function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response.text();
    } else {
        return Promise.reject(new Error(response.status +
                                        ": " + response.statusText));
    }
}

function callAjax() {
    let url = ..... // put url string here
    fetch(url, {credentials: 'include'}) // include credentials for c9 to c9
       .then(checkStatus)
       .then(function(responseText) {
            //success: do something with the responseText
        })
       .catch(function(error) {
           //error: do something with error
       });
}
        

JS (template)

Ajax fetch Code Skeleton (variation)

/* global fetch */ // listed outside module pattern
...
function checkStatus(response) {    // boiler plate code given out
   ...
}

function callAjax() {
    let url = ..... // put url string here
fetch(url, {credentials: 'include'}) // include credentials for c9 to c9
       .then(checkStatus)
       .then(handleResponse)
       .catch(handleError);
}

function handleResponse(responseText){
    //success: do something with the responseText
}

function handleError(error){
    //error: do something with error
}
      

JS (template)

Cross origin security concerns

Generally speaking, you can only send Ajax requests to the server that your page came from.

This is to prevent rogue javascript from being able to call out to any server and pull in whatever content it wants to.

This is a little bit of a concern for us, because we want you to be able to call to code on webster server to get new information, so we have to write special rules on webster to allow your programs to do what's called "Cross-Origin Request Sharing" or CORS.

ajax security image

Cross origin security concerns solution

Cloud9 -> Cloud9

If you are writing JavaScript that will call a server side application (.php) on Cloud 9, your fetch statement will start like this:


fetch(url, {credentials: 'include'}) // include credentials for c9 to c9
       

JS (template)

Cloud9 -> Webster

If you are writing JavaScript that will call a server side application (.php) on webster, your fetch statement will start like this:


 fetch(url, {mode: 'cors'}) // cors for cloud9 to webster
        

JS (template)

Ajax fetch example

/* global fetch */ // listed outside module pattern
...
function checkStatus(response) {  // boiler plate code given out
   ...
}

function callAjax(){
    let url = URLBASE + "duckystore.php?mode=ducks";
    fetch(url, {mode: 'cors'}) // mode cors for talking with webster
       .then(checkStatus)
       .then(loadDucksResponse)
       .catch(console.log);
}

function loadDucksResponse(responseText){
    //success: do something with the responseText
}
    

JS (template)

Summary: Why are promises/fetch useful?

The help deal with uncertainty in your code. You never know exactly what will happen when you make an Ajax call, so wrapping the call in a Promise is a nice way to deal with the uncertainty.

The paradigm is nice because you write the anonymous function that defines the promise, so you are the one who writes the code that determines whether the promise was 'fulfilled' or 'rejected'.

You also define what happens after the Promise fulfills with the then function, and what happens when it rejects in the catch function.