Exercise 5: JQuery, AJAX

The aim this laboratory is to use JQuery, AJAX and the DOM for dynamically modifying webpages.


Work through the W3Schools AJAX tutorial and then the W3Schools JQuery tutorial.

Setting up a simple server for AJAX

We will use Flask to create and serve web applications, but for now, AJAX requires a web server, so the requests will be properly formatted and managed. The live server extension is available to run a small web server on your computer, and will host and server the code you develop in VSCode. Set up live server in your VSCode environment, and then try working through the more advanced AJAX tutorial below.

AJAX tutorial

A more advance AJAX tutorial is available that walks you through applying AJAX with JQuery. Work through these exercises.

Study break Challenge: Creating a Text-based Calculator

Create a new web page, called calculator.html, from your template page.

  1. Add JavaScript to pop up a dialogue box that asks the user to enter a formula that they wish to calculate. Write code that parses this formula, performs the calculation, and pops up an alert with the answer. You may assume for now that the formula contains at most three operations.

    You will need to use the regular expression methods to parse, or break down, the string into its components, and type conversion to extract the numbers. When doing the parsing, remember to respect the precedence of the arithmetic operators. For example, if the user enters:

     15 + 4 x 3
    it should give the answer 27, not 57.

    You should not assume any particular convention for whitespace. So for example

     15+4 x  3
    should give the same result.

  2. Repeat the above task for arbitrary length formulae using an array as a Stack data structure (that is, using the push and pop methods). You will need three stacks: one (the input stack) to hold the parts of the input as it is parsed, one (the preorder stack) to hold the components of the formula in preorder format, and one (the answer stack) to accumulate the answer. (You may assume for now only natural numbers and no parentheses are used in the formula.)

    The algorithm proceeds as follows:

    Write code that prints the stacks out in the browser window at each step, as per the examples above, and then prints (in bold) the final answer.

  3. Challenge: Extend your code so that it also correctly treats parentheses and negative numbers.