cs304 logo

Class on Ajax and JSON

The Three-Tier Architecture

We've learned:

Today, we'll dynamically update the page by interacting with the server using Ajax.

Goal

By the end of today, you will be able to:

Plan

  1. Stuff from last time
  2. Structure of a Flask app
  3. Quiz Questions
  4. We'll review what we learned in the reading, but in a few chunks, deferring templating and event bubbling.
  5. We'll do some exercises comprising the goals for the day.

Reading Review

Quiz Questions

I would answer your quiz questions, but there were none!

Example: Collatz Sequence

I've created an example of a Flask app that uses Ajax to get and send data. It's in /cs304collatz. I'll run that example, so we can try it out, and then we'll explore the code.

Compare these URLs:

The Example

I'll run the code in ~cs304/pub/downloads/ajax/

Collatz app

Exercise: Your Sequence

  1. Copy the ajax directory to your account:
    cp -r ~cs304/pub/downloads/ajax/ ajax
  2. Look at the code. It's not long, and it's in the reading.
  3. Activate the venv and run the collatz-app.py file.
  4. Visit the buffer. Click on some numbers to try it out.
  5. Type in a URL like /getCollatzAjax/?num=25 and look at the response
  6. Open the Chrome Inspector and look at the network tab to get some insight about the request and the response
  7. Open the JS console and add a completely new number:
    
    addToList({in: 20, out: 10});
    

Updating the DOM

That updating of the DOM is incomplete. Shouldn't the new IN/OUT values replace the bold red numbers on the page? Do that.

Modify the response handler to update the page with the new values.

My solution:

Add these two lines to addToList():


        $("#result .x").text(obj.in);
        $("#result .y").text(obj.out);

like this


function addToList(obj) {
    if(obj.error) {
        $("#errors").empty().html('Error: '+obj.err);
    } else {
        $("<li>")
            .attr("data-num",obj.out)
            .text("the number "+obj.in+" produces "+obj.out)
            .appendTo("#collatzNumbers");
        $("#result .x").text(obj.in);
        $("#result .y").text(obj.out);
    }
}

This is in addToList-improved.js

A new sequence

  1. Come up with your own numeric sequence to replace the Collatz sequence.
  2. Write a route for that, and interact with it using $.get() or $.post(), maybe in the JS console.
  3. For an extra challenge, come up with a two-arg sequence, like z = 2*x+y, and augment the form with an extra input, etc.

Even More

It's useful to be able to navigate around the DOM. I'll give some examples using jQuery:

Summary

We've come a long way! We learned