Web Development

Dr Derek Bridge
School of Computer Science & Information Technology
University College Cork

Web Development I and II

Module codes: CS1115/CS5002 Web Development I
CS1116/CS5018 Web Development II
Credit weighting: 5 credits each

Objectives

  • Explain the role of server-side and client-side technologies;
  • Write simple server-side programs;
  • Write simple client-side programs.

Prerequisites

The prerequisite knowledge is HTML, CSS, HTTP, URLs, Python and SQL

Delivery

On-campus lectures Tuesdays 12-1pm, WGB 107
Fridays 1-2pm, WGB 107
On-campus labs Thursdays 2-4pm, WGB 110/
Thursdays 4-6pm, WGB 110,
starting in week 2
Private study At least 3 hrs per week

Study

Assessment

Continuous assessment: Server-side programming project, 50 marks
Continuous assessment: Client-side programming project, 50 marks

Plagiarism

  1. Plagiarism is presenting someone else's work as your own. It is a violation of UCC Policy and there are strict and severe penalties.
  2. You must read and comply with the UCC Policy on Plagiarism www.ucc.ie/en/exams/procedures-regulations/
  3. The Policy applies to all work submitted, including software.
  4. You can expect that your work will be checked for evidence of plagiarism or collusion.
  5. In some circumstances it may be acceptable to reuse a small amount of work by others, but only if you provide explicit acknowledgement and justification.
  6. If in doubt ask your module lecturer prior to submission. Better safe than sorry!

Students should be aware that the use of ChatGPT or Copilot or similar tools to generate text, code or diagrams without clear attribution will be considered an academic offence equivalent to plagiarism.

Copyright

The slides, screenshots, labs, videos and other resources are mine
(and UCC's)!

Please do not republish them anywhere!

Lecture 1: Objectives

We will look at some Python that we need:
some of it you know; a little is new.

  • Variables
  • Data types
    • integers, floats, booleans, strings
    • lists
    • dictionaries
  • Functions
  • Modules

Lecture 2: Objectives

  • learn to distinguish static web pages from dynamic web pages
  • learn to distinguish server-side programs from client-side programs
  • learn how to write routes in a simple Flask app

Client-server

The web has machines running client software and machines running server software.

Resources

Servers host many different kinds of resources.

Programs on the Web

  • Server-side: the program executes on the server
    • E.g. Google search, Amazon — anything that must consult a large database, stored on the server
    • Programming languages: e.g. Python, PHP, Java, C, …
  • Client-side: the program executes on the client
    • E.g. simple calculators, simple games, programs to make Web pages more interactive
    • Programming languages: e.g. JavaScript

Server-side programs

The client requests that a program be executed

Server-side programs

The server executes the program

Server-side programs

The response to the client is the outut from the program

Client-side programs

The client requests a program from the server

Client-side programs

The server sends a copy of the program to the client

Client-side programs

The client executes the program

Programs on the Web

Many web apps use both!

Flask

To learn server-side programming, we will use Flask.

Lecture 3: Objectives

  • learn how to render Jinja templates in Flask apps
  • learn how to use Jinja templates that extend other templates
  • become aware that Jinja templates can also contain if-statements and for-loops

Lecture 4: Objectives

  • learn how to write simple forms in HTML
  • learn how HTTP sends form data
  • learn how to write a Flask app that responds to form data

HTML forms

The form element contains 'controls' such as textfields, radio buttons, etc.

Most controls are specified using the input tag.
The type attribute specifies what kind of control:
Click to see all of them!

A few controls use a different tag,
e.g. textarea, select

Attributes


<input type="text" />
    

… allows many additional attributes, e.g.:
name
size
maxlength
value
placeholder

The name attribute

Most controls are useless unless given a name.

Why?
Because we'll be using their names in our Python.

The size attribute

By default, textfields are 20 chars wide, but optionally use the size attribute to change its width:

The maxlength attribute

By default, users can type as many chars as they want (irrespective of size), so optionally use maxlength to restrict this:

The value attribute

By default, textfields are initially empty, but optionally use the value to supply your own initial value:

The placeholder attribute

How do users know what they are supposed to type?

placeholder is good when you are short of space.

When the user presses submit…

When the user presses the submit button, the browser arranges the data in name/value pairs.

  • E.g. the user types Hugh and Jeegoh into the form
  • The browser arranges the data as follows:

given_name=Hugh
family_name=Jeegoh
    

…and behind the scenes

The browser also encodes the data using standard URL encoding.

This replaces spaces, slashes and other characters that are not allowed in URLs by their hexadecimal equivalents.

  • E.g. spaces are replaced by %20 (which may display as '+'); slashes by %2F
  • E.g. if the user types Ann and O Domini into the form, the browser arranges and encodes the data as follows:

given_name=Ann
family_name=O%20Domini
    

And then…

  • The browser then creates an HTTP request
    • The command (GET or POST) comes from the form's method attribute
    • The URL comes from the form's action attribute

GET method

If the method="get",
the data is joined by ampersands
and added to the end of the URL after a question mark:

The user's data is on the end of the URL.

POST method

If the method="post",
the data is in the HTTP request body:

The user's data is in the body of the request.

GET or POST?

Traditional Advice
GET POST
for a short form with few fields for a longer, more complex form, where encoding the form data in the URL would result in a URL that is too long
to allow the URL (with the form data) to be bookmarked, or used elsewhere for security, because encryption and other encodings of the data is possible when it is the HTTP body
where the outcome wouldn't differ if you issued the same request more than once for requests that make a change in the server (e.g. update a database)

GET or POST?

Flask programmers pretty much always use POST.

Where is the data sent?

This is given by the form's action attribute.

If we write action="", the data is sent back to same URL that the form came from.

Summary: Version 1

The user requests a form, fills it in and presses Submit. The browser sends the data to the server. The server executes the function using the data and sends back the response.

Summary: Version 2

The user requests a form, fills it in and presses Submit. The browser sends the data to the server. The server executes the function using the data and sends back the response.

Lecture 5: Objectives

  • consolidate what we learned in the previous lecture
  • learn how to validate form data
  • learn how to handle numeric input from forms

Lecture 6: Objectives

  • learn how to validate numeric form data
  • start to understand WTForms

try/except


try:
    weight = float(weight)
    height = float(height)
    ...
except ValueError:
    return render_template(..., error="Error!")
    

try-except (simplified)

  • If it successfully coerces the string into a float,
    • it executes the rest of the try block
    • it skips the except block
  • If the coercion fails,
    • it skips the rest of the try block
    • it executes the except block

Lecture 7: Objectives

  • consolidate understanding of WTForms
  • learn how to serve static resources (e.g. images, CSS) in Flask apps
  • learn how to link between pages in Flask apps

Lecture 8: Objectives

  • review our understanding of relational databases
  • learn how Flask can connect to a database
  • learn how Flask can query a database

Relational databases

  • A database is a repository of integrated data.
  • A relational database organises the data into tables.
  • Mathematically speaking, the tables are n-ary relations.
  • SQL (Structured Query Language) is a 'standard' language for defining and manipulating relational databases:
    • it is a data definition language — it has commands for creating and deleting tables; and
    • it is a data manipulation language — it has commands for inserting rows into tables, deleting rows, updating rows and retrieving rows.
  • We'll use SQLite — because it comes with Python.

Examples of tables

Enrolments
id code
123 CS456
234 CS345
234 CS456

SQL

Find the id's and names of all students who study CS345


        SELECT Students.id, Students.name
          FROM Students JOIN Enrolments
            ON Students.id = Enrolments.id
         WHERE Enrolments.code = "CS345";
    
Students.id Students.name
234 Julie Noted

Table of past and future gigs


DROP TABLE IF EXISTS gigs;

CREATE TABLE gigs 
(
    gig_id INTEGER PRIMARY KEY AUTOINCREMENT,
    band TEXT NOT NULL,
    gig_date TEXT NOT NULL
);
    

Example data


INSERT INTO gigs (band, gig_date)
VALUES ('Decaying Shroom', '2024-01-12'),
       ('Belated Tonic', '2024-01-21'),
       ('Dumpy Tension of the Divided Unicorn', '2024-02-10'),
       ('Belated Tonic', '2024-02-20'),
       ('Missing Roller and the Earl', '2024-02-26'),
       ('Glam Blizzard', '2024-03-07'),
       ('Piscatory Classroom', '2024-03-12'),
       ('Prickly Muse', '2024-03-20'),
       ('Interactive Children of the Phony Filth', '2024-03-29');
    
Band names produced by www.bandnamemaker.com

Lecture 9: Objectives

  • consolidate what we learned in the previous lecture
  • learn how to use Flask to insert data into a database

Lecture 10: Objectives

  • learn about statelessness, cookies and the different types of cookie
  • learn how to send and receive cookies in Flask

Statelessness

HTTP is a stateless protocol:
each request is independent
— by default, the server has no memory of previous requests

Statelessness

  • "I love stateless systems."
  • "Don't they have drawbacks?"
  • "Don't what have drawbacks?"

State management

IP addresses keep a record of clients' IP addresses
Cookies send the client some data, which it sends back to you
URL rewriting include a user identifier in the query part of a URL
Hidden fields include a non-visible field in forms

Cookies for state management

Cookies example, part I

  • Your browser sends a request to www.amazon.co.uk:
    GET /index.html
  • A server-side program stores information, e.g. in its database, about your visit
  • The server's response includes a cookie:
    HTTP/3.0 200 OK
    Set-Cookie: id=cust123; path=/; domain=.amazon.co.uk
  • If cookies are enabled in your browser, your browser stores the cookie

Cookies example, part II

  • On a subsequent occasion, you visit www.amazon.co.uk again (or the amazon.co.uk domain)
  • Your browser includes the cookie in the request:
    GET /index.html
    Cookie: id=cust123
  • On detection of the cookie, server-side programs know that you have made requests on previous occasions and can use the cookie data, e.g. to look you up in the database
  • Q: What are the problems of trying to identify users using cookies?

Two types of cookie

  • Persistent cookies:
    • The server includes an expiry date or maximum age in the cookie:
      HTTP/3.0 200 OK
      Set-Cookie: id=cust123;
              expires=Sun, 17-Jan-2044 19:14:07 GMT;         path=/; domain=.amazon.co.uk
    • The browser stores the cookie on the client's hard disk
    • The browser deletes the cookie when it expires
  • Persistent cookies are useful for identifying clients which have contacted the server in the past

Two types of cookie

  • In-memory cookies:
    • The server does not include an expiry date:
      HTTP/3.0 200 OK
      Set-Cookie: id=cust123; path=/; domain=.amazon.co.uk
    • The browser (ordinarily) stores the cookie in main memory
    • The browser (ordinarily) deletes the cookie when the browser is shut down
  • In-memory cookies are useful for sessions

Lecture 11: Objectives

  • learn about sessions
  • learn how to work with sessions in Flask
  • learn how to use sessions in Flask to implement a simple shopping cart

Table of wines


DROP TABLE IF EXISTS wines;

CREATE TABLE wines 
(
    wine_id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    price REAL NOT NULL,
    description TEXT
);
    

Example data


INSERT INTO wines (name, price, description)
VALUES
  ('Dingo Dribble', 12.33, 'Goes well with a snake steak.'),
  ('Emu Emission', 17.99, 'A spunky wine for every occasion!'),
  ('Koala Kool-aid', 12.33, 'With a hint of eucalyptus.'),
  ('Platypus Pish', 15.99, 'A fizzy and frothy concoction.'),
  ('Roo Runoff', 8.99, 'Quite acidic.'),
  ('Wombat Waz', 10.99, 'The taste of the outback.');
    

Sessions

  • A session is a sequence of requests from the same client within a short period of time
  • Although the user may access different pages from the web site, we may want to:
    • track the client, i.e. identify which client is making requests and
    • keep user-specific data across the pages visited

Session ids

  • A session will have a unique identifier — its unique session id (SID)
  • The SID is:
    • created by the server
    • sent to the client and
    • sent back to the server whenever the client makes a request
    A cookie is ideal for this.

Session state

  • Session state: other data that we keep about this session, e.g.
    • whether the user is logged
    • if the user is logged in, her user id
    • the contents of her shopping cart
    • etc.
  • Client-side sessions: the session state is sent back-and-forth in cookies (the default in Flask)
  • Server-side sessions: the session state is stored in a file or database on the server (what we will be using)

Lecture 12: Objectives

  • learn how to implement user authentication in Flask

User authentication

  • Registration
  • Login: the user's id is stored in the session state
  • Logout: clear the session state
  • Views that require authentication: check whether a user id is in the session state

Lecture 13: Objectives

  • revise the concept of client-side programming
  • compare some JavaScript with Python
  • write a JavaScript program for drawing in the canvas
(Acknowledgment:
This way of introducing JavaScript is inspired by the methods of Seb Lee-Delisle.)

Server-side programs

The response to the client is the outut from the program

Client-side programs

The client executes the program

Check your understanding

Consider the Hello World program that we wrote in the lecture:

  • What will the server do with this JavaScript program?
  • What will the browser do with this JavaScript program?
  • What goes between the <script> start tag and </script> end tag?
  • Are those semi-colons needed?
  • In general, your users would prefer you to avoid writing programs that use the window.alert() method. Why?
  • Suppose this program is on our server in Cork. Someone in Australia requests it
    Whose time/date do they see?

JavaScript

  • A programming language in which we write programs designed to be embedded in other software applications
  • The core language (sometimes called ECMAScript) has:
    • typical operators, expressions and statements; and
    • core objects, such as Array, Date and Math
    The core is standardized
  • JavaScript and Java are both partly inspired by C but otherwise unrelated

Client-side JavaScript

  • Client-side Javascript extends the core with objects to:
    • control the browser
    • interact with the user
    • communicate with the server and
    • alter the document content
    These extensions were less standardized — might differ from browser to browser
  • Other extensions of the core allow JavaScript programs to be used in servers, in PDF documents, …

Variables

JavaScript variables should be explicitly declared
(using let or const)

Variables, again

But JavaScript does allow you to combine variable declaration with initialization

Comments

Single-line comments

Multiline comments

Function definitions

NB: Python uses indentation to denote blocks of code;
JavaScript uses curly braces

Drawing a coloured rectangle

  • context.fillRect(x, y, width, height)
    x The x-coordinate of the upper-left corner of the rectangle
    y The y-coordinate of the upper-left corner of the rectangle
    width The width of the rectangle, in pixels
    height The height of the rectangle, in pixels

Clearing a rectangle

  • context.clearRect(x, y, width, height)
    x The x-coordinate of the upper-left corner of the rectangle to clear
    y The y-coordinate of the upper-left corner of the rectangle to clear
    width The width of the rectangle to clear, in pixels
    height The height of the rectangle to clear, in pixels

Animation in Javascript

  • window.requestAnimationFrame(function)
    function The function that will be executed
  • tells the browser we are doing an animation
  • tells the browser to call the function before it next repaints the screen
  • depends on client hardware, but typically 60 times per second

Lecture 14: Objectives

  • learn how to write JavaScript if-statements and for-loops
  • learn the differences between strongly-typed and weakly-typed programming languages
  • learn how to use JavaScript lists and objects

Conditional statements

In the JavaScript, note:

  • else if instead of elif
  • the round parentheses
  • the curly braces
  • the three equal signs!

Also, where Python uses and, or and not, JavaScript uses &&, || and !

Type coercion

Python is a strongly-typed language,
whereas JavaScript is weakly-typed

Type coercion

  • JavaScript's type coercion is bizarre and causes many programming errors.
  • Avoid JavaScript type coercion in equality tests by using identity (===), instead of equality (==)
    • Then in the JavaScript on the previous slide, both tests would be false

JavaScript objects

  • At their simplest, objects in JavaScript are bundles of comma-separated properties, e.g.:
    
    let twinA = {
        firstname : "John",
        surname : "Grimes",
        age : 32
    }
    
    let twinB = {
        firstname : "Edward",
        surname : "Grimes",
        age : 32
    }
  • To refer to an object's properties, use the dot notation, e.g. twinA.firstname

Lists and arrays

The 'equivalent' of a Python list is a JavaScript array

(JavaScript arrays are very similar to Python lists
but not so similar to arrays in languages such as C or Java)

for loops

Using a loop to 'visit' each item in a list or array

Using a loop to count, e.g. from 0 to 9 inclusive

Lecture 15: Objectives

  • learn the concept of event-driven programs
  • learn how to use JavaScript to register event listeners

Calling a function

  • Defining a function, e.g.:
    
    function annoy_me() {
        window.alert("Annoying, huh?");
    }
  • Executing a function by calling it, e.g.:
    
    annoy_me();
  • Arranging for a function to be executed whenever an event occurs, e.g.:
    
    window.addEventListener("click", annoy_me, false);

Event-driven programming

  • Programs that use this idea are called event-driven programs
  • In client-side JavaScript, events include:
    • when the web page has finished loading
    • when the user clicks on a hyperlink
    • when the user clicks on a button
    • when the user moves the mouse into or out of a certain region of the screen
    • and so on
  • The function that runs is called the event listener (or event handler)

Event objects

  • When an event occurs, relevant information about the event is stored in an object
  • E.g. in the case of a mouse click, the event has properties that include
    • clientX and clientY — the viewport coordinates of the mouse click
  • The event handler can access these properties, e.g.:
    
    function annoy_me(event) {
        window.alert("Your click was at " + event.clientX + " " + event.clientY );
    }
    
    window.addEventListener("click", annoy_me, false);

Question

In fact, our JavaScript programs already contained an example of event-driven programming
Q: Where?


document.addEventListener("DOMContentLoaded", init, false);

Lecture 16: Objectives

  • consolidate our understanding of event-driven programs with another example
  • learn how to draw and animate an image sprite
  • learn how to draw a background from a tileset

Drawing an image

  • declare and initialize a variable, e.g.:
    
    let playerImage = new Image();
  • load the image (usually in init), e.g.:
    
    playerImage.src = "image.png";
  • draw the image on the canvas (usually in draw):
    
    context.drawImage(playerImage, 10, 20)
    — here we place the top left of the image on the canvas at 10 pixels across and 20 pixels down

Drawing part of an image

  • context.drawImage(image,
                      sx, sy, swidth, sheight,
                      dx, dy, dwidth, dheight)
    image The image we are extracting from
    sx, sy, swidth, sheight The x- and y-coordinates of the upper-left corner of the part of the image that we are drawing, and the width and height
    dx, dy, dwidth, dheight The x- and y-coordinates of where in the canvas we want to draw the upper-left corner of the part of the image that we are drawing, and the width and height

Loading images

  • In JavaScript, images (and other assets such as audio files) are loaded asynchronously
    • It does not wait for the image to load!
  • This can cause problems, e.g. when trying to draw
  • One solution is to use my function that ensures that all assets are loaded before continuing with the rest of the program

Lecture 17: Objectives

  • learn how to use JavaScript to change the content and appearance of a web page

Client-side Javascript

Client-side JavaScript comprises the core language plus the BOM and DOM.

The Browser Object Model

  • The BOM is an application programming interface (API) for browsers:
    • window object
      • Q: Where have we used this already?
    • navigator object
    • location object
    • screen object and
    • history object
  • As part of HTML5, the BOM is increasingly standard across modern browsers

The Document Object Model

  • The DOM is an API for HTML documents (and XML documents):
    • allows you to use JavaScript to change the content and appearance of a web page without reloading it
  • Treats the page as a hierarchy of different types of node:
    • allows you to use JavaScript to remove, replace, insert or change the nodes

Hierarchical Structure

Note the different types of node:
the document node, the element nodes, and the text nodes

Finding element nodes

  • element = document.querySelector("...");
    Returns the first element in the document that matches the CSS selector, or null if no element matches the CSS selector
  • elements = document.querySelectorAll("...");
    Returns an array-like collection of all elements in the document that match the CSS selector

Examples


<html lang="en">
    <head>
        <title>Lorem ipsum</title>
    </head>
    <body>
        <section id="sectA">
            <p class="opening">Lorem ipsum dolor sit amet consectetuer adipiscing.</p>
            <p class="closing">Lorem ipsum dolor sit amet consectetuer adipiscing.</p>
        </section>
        <section id="sectB">
            <p class="opening">Lorem ipsum dolor sit amet consectetuer adipiscing.</p>
            <p>Lorem ipsum dolor sit amet consectetuer adipiscing.</p>
            <p class="closing">Lorem ipsum dolor sit amet consectetuer adipiscing.</p>
        </section>
    </body>
</html>

What gets retrieved?


element = document.querySelector(".opening");
The paragraph is retrieved.

What gets retrieved?


elements = document.querySelectorAll(".opening");
Both opening paragraphs are retrieved.

What gets retrieved?


elements = document.querySelectorAll("#sectB .opening");
The opening paragraph of the second section is retrieved.

NB: It's still an 'array'.

Creating new element nodes

  • E.g. to create a new p element node:
    
    new_element = document.createElement("p");
  • E.g. adding the node into the tree:
  • 
    some_element.appendChild(new_element);
    — it becomes the last child.
  • Others: insertBefore, replaceChild, removeChild

Changing the text in a node

  • E.g. putting some text into a new node:
    
    new_element.innerHTML = "Third paragraph";
  • In fact, innerHTML is even more powerful than this example suggests

Properties of element nodes

  • As you know, HTML elements may have attributes
    Q: Give examples
  • JavaScript can retrieve and change attribute values by accessing and setting object properties
  • E.g.
    
    some_element.id = "new_id";

Changing the class attribute

  • We've seen how to change the id, src and other attributes
  • To change the class attribute:
    • This doesn't work:
      
      some_node.class = "new_class";
    • You must write this:
      
      some_node.className = "new_class";

Changing an element's CSS

  • JavaScript can dynamically change an element's CSS by setting its style
  • E.g.
    
    some_element.style.color = "blue";
  • CSS often uses hyphens in CSS property names but JavaScript uses camel case, e.g.
    CSSJavaScript
    background-color style.backgroundColor
    font-family style.fontFamily

Lecture 18: Objectives

  • to write client-side JavaScript that handles forms

Trade-offs

  • In one version of our BMI program,
    • the data validation is done server-side
    • the calculation is done server-side
  • In the other version, both are done client-side
  • We could even do some other mix of the two.
  • Q: What are the cost-benefit trade-offs here?
  • Q: When must we use a server-side approach?

Lecture 19: Objectives

  • learn how client-side JavaScript can send HTTP requests
  • learn what Ajax is and how it is used in modern web apps

HTTP requests

A browser sends an HTTP request to a server…

  • when the user clicks on a hyperlink
  • when the user enters a URL into the Location box
  • when the browser submits a form to the server

But a client-side script can also send a HTTP request

XMLHttpRequest objects

Summary of what your client-side script needs to do in order to send an HTTP request:

  1. Create the request object
  2. Register a function that will handle the response (assuming asynchronous response handling)
  3. Specify the URL and the HTTP method (e.g. GET or POST)
  4. Optionally, specify any special headers that are to be sent
  5. Send the request

XMLHttpRequest example


// Create the request object
let xhttp;
xhttp = new XMLHttpRequest();

// Register a function that will handle the response:
xhttp.addEventListener("readystatechange", handle_response, false);

// Specify the URL and the HTTP method (e.g. GET or POST):
xhttp.open("GET", url, true);

// Optionally, specify any special headers that are to be sent, e.g.:
xhttp.setRequestHeader("User-Agent", "XMLHttpRequest");

// Send the request:
xhttp.send(null);

The response

  • The same object that was used for the request is also used for the response (in our case xhttp)
  • You can use the following properties and methods:
    • xhttp.status: the status code sent back by the server
      Q: What number are you hoping for?
    • xhttp.getResponseHeader("…"): to access the specified response header
    • xhttp.getAllResponseHeaders(): to access all response headers as an array
    • xhttp.responseText: to access the body of the server's response as a string
    • xhttp.responseXML: to access the body of the server's response as XML (inc. HTML)

Typical function to handle the response


function handle_response() {
    // Check that the response has fully arrived
    if ( xhttp.readyState === 4 ) {
        // Check the request was successful
        if ( xhttp.status === 200 ) {
            // do whatever you want to do with 
            // xhttp.responseText or xhttp.responseXML
        } else {
            console.log("Problem " + xhttp.status);
        }
    }
}

Ajax

Asychronous JavaScript and XML (Ajax):

  • It's not a programming language
  • It's a way of using XMLHttpRequest
  • Classically, if the content of a page needs to change, the whole page is fetched again from the server
    • Think of all the activities involved — they will take considerable time
  • The idea in Ajax is that client-side JavaScript will:
    • send an asynchronous XMLHttpRequest to fetch from the server just the content that has changed
    • use the response to update relevant parts of the page
  • Smaller amounts of data are fetched — this takes less time

Uses of Ajax

  • Auto-suggestions in Google search box
  • Status updates in, e.g., Twitter
  • Counts of numbers of likes in, e.g., Twitter

Simple Ajax Examples

  • Client-side game sends a score to a server-side program to update database of scores
  • Client-side game regularly asks the server how many likes the game has received

Single Page Applications

Ajax is used to build single-page apps

  • A single HTML web page uses Ajax to rewrite the current page, rather than loading new pages

Problems with Ajax

  • The user typically does not know when requests are being made
  • When the content changes, the URL doesn't: you cannot easily bookmark different 'versions' of the page
  • Similarly, the Back button and History list of your browser may not function as some users would expect them to
  • By fetching small amounts of content, Ajax is supposed to be faster
    Q: But why might it, in fact, slow things down?

Final comment on this

  • Code that uses XMLHttpRequests is quite convoluted
  • There is a new alternative using the fetch function
  • However, using this properly requires understanding the (considerable) complexities of JavaScript promises

Lecture 20: Objectives

  • learn where to go next in your voyage into server-side programming
  • learn where to go next in your voyage into client-side programming

Flask: what next?

  • database abstraction layers and object relational mappers (e.g. SQLAlchemy)
  • security
  • scaling up (e.g. blueprints)
  • testing

Flask: alternatives

  • Django (Python)
  • Spring MVC (Java)
  • Ruby on Rails
  • Laravel, Symfony and lots more (PHP)

JavaScript: what next?

  • we avoided its complexities (classes, prototypes, this, …)
  • we missed lots of cool stuff (drag-and-drop, local storage, web workers, web sockets)
  • JavaScript is being used server-side too (e.g. node.js)

JavaScript libraries

  • jQuery
  • React JS
  • Vue.js
  • Backbone.js
  • Angular

Other

  • CSS frameworks, e.g. Bootstrap
  • Testing frameworks, e.g. Selenium

G'luck!