Topic 7 - Using the HTML DOM


Further AJAX topics

The main topic this week is the DOM but before we look at that, we just need to cover a couple of additional AJAX topics related to our Web Services and HTTP topic from last week, namely:

How to test the HTTP status code from an AJAX client

It is easy to test the HTTP status code from a web service client. If you are using AJAX you can simply use the status property of e.target (the original XMLHttpRequest object) in the callback, for example:

ajaxConnection.addEventListener("load", e => {
    if(e.target.status==404)
    {
        alert("The song was not found!");
    }
});

POST requests from AJAX

To send POST requests from AJAX, you need to create a FormData object and then append each item of POST data to it. The example below will create three items of POST data, flightnumber, origin and destination, and send them to newflight.php. Note how the FormData object is supplied as a parameter to the ajaxConnection.send() function. In the PHP script, we'd then read the data using $_POST["flightnumber"], $_POST["origin"] and $_POST["destination"].

var ajaxConnection = new XMLHttpRequest();
var data = new FormData();
data.append("flightnumber", "SA177");
data.append("origin", "London");
data.append("destination", "Denver");
ajaxConnection.addEventListener("load", { ... callback function ... } );
ajaxConnection.open("POST", "newflight.php");
ajaxConnection.send(data);

Querying and Manipulating HTML documents using the DOM

In previous units, you've seen the innerHTML property which can be used to read, or change, the text within an HTML element. You've also looked at simple use of the Document Object Model (DOM) to access elements on a web page - specifically the use of getElementById() to access a specific page element using its ID.

However that's just the start: the DOM offers a whole range of ways to read and manipulate HTML pages or XML data. To understand how you can use DOM for document manipulation, you must understand the concept of nodes, which we will discuss below. The examples below use the DOM to manipulate HTML documents, however, more generally, the DOM is used for accessing and manipulating XML documents. An HTML web page is a particular, specific type of XML document. So, as well as using the DOM to query and manipulate web pages, we can use it in a more general sense to query and manipulate XML. In AJAX, this latter use of the DOM is used extensively.

The Concept of Nodes

Example of Nodes Terminology

<body>

<p> Welcome to the <em>wonderful!</em> world of dynamic text!</p>
</body>
  • The paragraph is a child node of the body
  • The paragraph contains three of its own child nodes:
  • The em itself contains one child node:
  • Nodes Hierarchy Diagram: Tree view

    <body>
    <p> Welcome to the <em>wonderful!</em> world of dynamic text!</p>
    
    </body>
    
    Nodes

    Querying the Node Structure of a Document

    Example

    Adding a new node

    Example

    Replacing an existing node

    Example

    Getting all elements of a particular type

    Example

    Removing nodes

    Other useful features of the DOM

    (Source: Quirksmode, a very useful reference site for JavaScript and the DOM)

    More advanced exercise - Using the DOM to add Order Functionality to your HitTastic! AJAX site

    Do not attempt this unless you have done all exercises from the first AJAX topic last time, and are comfortable with the material on DOM nodes from this week. Also ensure that you are completely up to date with Sessions 1 to 4.

    Inspecting elements

    The inspect functionality in the browser will help you see what's going on - try it as you do this exercise - right click on an element. Inspecting helps you to see the actual current DOM structure of the page - including any dynamically-created elements.

    Questions

    You are going to extend the functionality of your AJAX-based HT-Tracks website so that the user is able to order physical copies (CD, vinyl) of songs.

    1. Extend your Slim web service to feature an "order" route (e.g. /song/{id}/order). This should reduce the quantity of that song by one, and add an entry into the "orders" table containing the song ID and a quantity of 1.
    2. Make a copy, in a new file, of your existing HT-Tracks AJAX page. Delete all the existing code in the foreach loop.
    3. Add code to your AJAX callback function so that it creates a DOM paragraph (p) element for each hit returned.
    4. Within this p, create: To make sure that the button is an input with a type of "button", you need to set the "type" property to "button", i.e. if btn is your button, then you can use:
      btn.type = "button";
    5. Specify the text on the button by setting the "value" property:
      btn.value="Order!";
    6. Set up a "click" event handler for the button. as an arrow function, e.g:
      btn.addEventListener ("click", e => 
              { 
      
                      // fill in your arrow function here.
                      // It should call your "order" web service route, passing in the ID of the current song.
      
              } 
      );
      
      This will set the "click" handler of the button to be an arrow function.
    7. Add each paragraph to the results div using appendChild().
    8. You can now complete the arrow function which runs when the user clicks the button. Use AJAX to call the "order" route of your web service. You will need to call the web service using a method of POST (see above), though in this case you will not need to send any FormData.
    9. The callback to the AJAX order request should display a "Successfully ordered" message, e.g. in an alert box.
    10. Add error handling to the "order" route of your web service so that if the required song is out of stock, a 404 is returned.
    11. Alter your AJAX front end to check for a 404 from the "order" route of your web service. In the callback, display a different message depending on whether the song was bought successfully or not.
    12. More advanced: Alter your "order" route to be able to order more than one copy of the song (receive the quantity as POST data). Update your AJAX front end to allow the user to enter the quantity, and send the entered quantity to the web service. As this is an advanced question, I am leaving it up to you to figure out how to do this but if you are really stuck, I will give you some hints.