CMPS 2680 - Week 13 notes

Notes Home Monday - Project 2 review Wednesday Friday

Wednesday

AJAX

Ex 1: A file request (without AJAX)

This request is simply retrieving a file stored on the server. It's not much different from clicking a link to the file. Instead, let's try it with AJAX:

Ex 2: a file request (with AJAX)

Ex 3: A form request (without AJAX)

First name:
Last name:
Access code:

This form actually does interact with server-side script (written with PHP), but the form submit causes the page to redirect.

Ex 4: form with AJAX

This version uses AJAX to submit the form below without redirecting the browser to a new page. Doing this requires:

First name:
Last name:
Access code:

Friday

jQuery and AJAX

jQuery is a JavaScript library that aims to simplify common tasks in web programming. These include DOM operations, animations, event handling, and even AJAX. Note that this is a JavaScript library; just about anything possible in jQuery is also possible with plain old JavaScript, but the ease of use and convenient syntax can save you development time and encourage you to follow good design patterns.

Linking to jQuery

Like any external JavaScript file, you need to include jQuery in your page source to make use of it. You could save the jQuery .js files to your web server and link to them there, but this isn't always a good idea. Instead, you can leverage the content delivery network (CDN) and simply link to a version hosted by someone else. Unlike hotlinking with images or videos, linking to a CDN's version of a JS library is usually beneficial: you don't have to host the file or pay for its bandwidth, and so many sites use it, the library files are extremely likely to end up in caches at every stage between your device and the server.

To use jQuery in your page, visit the jQuery CDN page and click on the version you want to use. In general, the latest "minified" version is suitable. Clicking the link will open a dialogue window with a code snippet for you to copy and paste into your HTML file. At the time of this writing, the jQuery Core 3.6.0 minified snippet looks like this:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" 
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 
        crossorigin="anonymous">
</script>

jQuery selectors

jQuery can utilize selectors, a little like CSS, to access elements and perform DOM operations on them. To change the content of an element named blogpost in vanilla JavaScript, it would look like:

document.getElementById("blogpost").innerHTML = "<b>New content!</b>";

With jQuery, this becomes:

$("#blogpost").html("<b>New content!</b>");

You can use these selectors for all kinds of things. This will give every paragraph a random background color using the random color function from step 9 of this demo:

$("p").css("background-color", getRandomHexColor())
Note that this changes all paragraphs to the same background color. To give each one its own random color, we can instead execute:
$("p").each(function () {
    $(this).css("background-color", getRandomHexColor());
});

jQuery and AJAX

jQuery also provides a nice, cross-browser-compatible approach for using AJAX. For example, to use my secret name web service with vanilla JavaScript, this looks like:


let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    let data = JSON.parse(this.responseText);
    document.getElementById("someDiv").innerHTML = data.fname + " " + data.lname;
  }
};
xhttp.open("POST", "../demos/secretname.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
let parameters = "fname=Nick&lname=Toothman&accesscode=2680S22";

xhttp.send(parameters);

with jQuery, this becomes:


$.post(
  "../demos/secretname.php", // Argument 1: URL to post to
  {                          // Argument 2: Data (as an object) to send
    name: 'Nick',
    lname: 'Toothman',
    accesscode: '2680S22'
  },
  function(data, status) {   // Argument 3: callback event handler
    if (status == "success") {
      $("#someDiv").html(data.fname + " " + data.lname);
    }
  }
);

See the following for excellent tutorials on jQuery:

For demonstration, here is the same form example from Monday, using jQuery in the scripting portions:

Ex 5: jQuery with AJAX

First name:
Last name:
Access code: