7401ICT: Client-side programming


(Under construction)

Introduction | JavaScript | Ajax | jQuery | Django

Introduction

The need for client-side programming:

JavaScript

JavaScript is a programming language that normally runs inside a Web browser. It adds client-side behaviour to the content and presentation provided by (X)HTML and CSS.

References

There are many bad texts on JavaScript! Here are some OK ones:

Summary

Events

In Web applications, JavaScript actions are normally invoked when one of the following events occur:

Actions

Typical actions that may be taken when events occur are to:

Examples

See the 2503ICT Web Programming lecture notes for a set of small examples.

(The server-side code in these examples is written in PHP, but it should still be quite understandabe.)

Ajax

Asynchronous JavaScript and XML (Ajax) is a new programming technique for developing dynamic and responsive Web applications. Some well-known applications that use Ajax include:

The main characteristics of Ajax applications are the following:

Ajax implementations are based on:

References

Dozens, maybe hundreds, of Ajax tutorials exist on the Web; just search for "Ajax tutorial".

Examples

Example 1

This example illustrates immediate and asynchronous text responses.

Example 2 (incomplete)

This example illustrates a JSON value response. JSON is described below. Basically, JSON is a format for structured data constructed from booleans, numbers and strings, combined using indexed and associative arrays (arrays and objects in JavaScript terminology), e.g., ["a", "b", {"c": 100}].

The XMLHttpRequest class

Properties

onreadystatechange contains a function of no arguments that is invoked whenever the server sends a response
readyState integers from 0 to 4, indicating progress, where 4 means "complete"
status 200 is OK; 404 if the page is not found
statusText string describing the status
responseText contains response data as a string
responseXml contains response data as an XML file, DOM methods used to extract data

Methods

open(method, url, async) method: type of request - GET or POST
url: the location of the file, with a path
async: true (asynchronous) or false (synchronous)
optionally, a login and a password may be added to arguments
setRequestHeader(header, value) sets request header
send(data) data sent with POST command, null for a GET command
getAllResponseHeaders() returns all response headers
getResponseHeader(header) returns value of given response header
abort() cancels the current request

More detailed descriptions of the XMLHttpRequest class may be found at:

jQuery

Frameworks

Many frameworks have been implemented to support and simplify the development of Ajax applications. A list can be found at Wikipedia. Different frameworks allow applications to be developed in different languages, not just JavaScript, but also Java, PHP, Python, .NET, etc. Some frameworks allow data to be transferred as JSON or plain text instead of XML. Two PHP frameworks are xajax and Sajax. The Google Web Toolkit allows you to write Ajax applications in Java. Dojo, jQuery and Prototype are three popular toolkits for writing Ajax applications. There are many others. Comparing these frameworks is difficult. We describe jQuery as it currently seems to be the most widely used framework.

Summary

jQuery is a very widely used JavaScript library. The main purposes of the jQuery library seem to be the following:

  1. Separating JavaScript code (behaviour) from HTML documents (content).
  2. Simplifying the task of writing JavaScript in general and Ajax applications in particular.

In more detail, jQuery makes it easy to find elements of a document, to manipulate those elements by adding content, editing HTML attributes and CSS properties, defining event handlers, and performing animations. It simplifies the task of writing Ajax applications using asynchronous HTTP requests and provides general utility functions for working with objects and arrays. Further, it hides JavaScript differences between browsers.

References

Tutorial

We start by following the tutorial How jQuery Works.

Refer to minified jquery code in your applications either locally (minimises network traffic) or from central server (increases likelihood that code is already in user's cache). Possible central servers are http://code.jquery.com/jquery-1.6.4.min.js and http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js. Locally, the server is http://dwarf.ict.griffith.edu.au/~s352978/lib/jquery.min.js (and jquery.js).

jQuery defines a single global function named jQuery() aka $(). The possible arguments of jQuery() are:

  1. CSS selector, e.g., var divs = $("div.alert");
  2. Window or document or element object
  3. String of HTML text, e.g., var img = $("", {src: url, css:{borderWidth:5}, click: handleClick}});
  4. Function, which is invoked when the document has been loaded.
The function jQuery() returns jQuery objects, to which methods may be applied.

Now, suppose you have a document like this:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
    <script src="jquery.js"></script>
    <script>jQuery code</script>
  </body>
</html>

Let's see what happens when we add code to the second <script> element:

$(document).ready(function() {
  // Code to execute when document is loaded
  $("a").click(function(event) { alert("Welcome!"); });
  });

This adds an event handler to each <a> element in the document, so when we click on the link, an alert box is displayed, before we go to the main jQuery page. It's similar to writing this:

<a href="" onclick="alert('Welcome!')">Link</a>

except that we don't need to add an onclick attribute to every link.

In fact, the above jQuery code can be written even more compactly:

$(function() {
  $("a").click(function(event) { alert("Welcome!"); });
  });

For every JavaScript event such as onclick, onchange, etc., there is an equivalent jQuery function click(), change(), etc.

Another common task is adding (or removing) class attributes to (or from) elements to influence how they are styled. Suppose the document head contains:

<style> 
  .bold { font-weight: bold; }
  .red  { color: red; }  
</style>

Then we can make every link appear in bold by adding the following to the second <script> element:

$("a").addClass("bold");

This example can be generalised by using an arbitrary CSS selector as the argument of $():

$(".list li").addClass("red");

This adds the class "red" to every list item in the list with class="list".

There's a similar removeClass() function.

Simple animations can be implemented using methods show() and hide() with arguments "slow" and "fast". There are many other animation methods.

Note how these examples allow us to avoid writing style attributes and event handlers in our documents, thus separating presentation and behaviour from content.

See this simple example, which illustrates these methods.

The tutorial Getting Started with jQuery expands on these techniques and introduces many new ones.

For example, jQuery has methods attr() for getting and setting attribute values of elements, css() for adding styles to elements, hasClass() for testing for classes of elements, addClass() and removeClass() for adding and removing classes of elements, val() for getting and setting the value attribute (or selection state) of form elements. Methods text() and html() are used to get or set the plain text or HTML content of one or more elements.

Examples:

$("form").attr("action");            // get the action of the first form
$("#icon").attr("src", "icon.gif");  // set the src attribute
$("#banner").attr({src:"banner.gif", // set 4 attributes at once
                   alt:"Advertisement",
                   width:720, height:64});
$("div.note").css("border", "solid black 2px"); // set the CSS border style
$("#surname").val();                            // get the value of a text field
$("#email").val("Invalid email address");       // Set value of a text field
$("head title").text();              // get document title 
$("head title").text("New heading"); // set document title

jQuery is designed in part to simplify the task of writing Ajax applications. The Ajax functions and methods allow applications to load data asynchronously from the server withoout a browser page refresh.

The Ajax functions and methods are described in the jQuery documentation. Perhaps the three most important functions are ajax(), get() and post(), which perform an asynchronous HTTP request, load data from the server using an HTTP GET request, and load data from the server using a HTTP POST request, respectively. Functions get() and post() are basically simpler ways of calling function ajax().

Function get() takes a URL, a map or string that is sent to the server with the request, a callback function that is executed if the request succeeds, and the type of data expected from the server (xml, json, script or html). The callback function is passed the return data (xml element, text string, JavaScript file or JSON object) depending on the MIME type of the response. It is also passed the text status of the response.

The following example omits the input and result type arguments.

$.get('test.html', function(data) {
  $('#result').html(data);
  alert('Data was returned.');
  });

Function post() takes the same four arguments as function get(). The callback function takes an additional "jqXHTR" object, an extended XMLHttpRequest object.

Here is a simple example:

$.post('test.php', 
  {name: "John", time: "2pm"},  
  function(data) {
    $('#result').html(data);
    alert('Data loaded: ' + data);
  }, "xml");

This rate me example is a very simple illustration of the use of these functions taken from the above tutorial. It invites the user to rate the current page on a scale of 1 to 5. Selecting a rating initiates an asynchronous HTTP request to the script rateme.php, which stores the rating and returns the average and number of past ratings.

In a more realistic example, the results might be appended to the page content instead of replacing the page content.

Note how the JavaScript code in index.php avoids all references to XMLHttpRequest objects and properties such as readyStatus of these objects, thus simplifying the task of writing Ajax applications.

It is possible to extend jQuery by writing plugins.

These notes just touch on the features of jQuery. To do any serious programming, you really need to refer to the documentation or to Flanagan's text.

Django

There are several tutorials on combining Django with JavaScript and Ajax and jQuery (search for "django javascript ajax jquery" or similar). One example is AJAX in Django with jQuery.