JQuery, and AJAX
CITS3403 Agile Web Develpopment
2023 Semester 2Unit Coordinator: Tim French
jQuery
jQuery is the most popular javascript library in the world.
It was built by John Resig in 2006, and is available on the MIT license.
The jQuery library has features for
l HTML/DOM manipulation
l CSS manipulation
l HTML event handling
l Effects and animations
l AJAX message handling
l Some utilities
jQuery, like Bootstrap, is most commonly accessed through a CDN:
jQuery Syntax
Basic jQuery syntax is $(selector).action(), where:
l $ is an abbreviation for jQuery. It can be changed using $.noConflict()
l selector is a query to find HTML elements, much like in CSS
l action is a jQuery function to be applied to the selected elements.
jQuery Events
jQuery event notation assigns a javascript
function to DOM events.
For example to assign a click event to all
paragraphs, we would use:
$(“p”).click(function(){//code});
jQuery events also include
$(document).ready()to force jQuery to
wait until the document is fully loaded.
The on() method allows multiple events to be
assigned to a given selector.
jQuery Effects
jQuery implements some useful effects, including hide, show, fade, slide
and animate.
These methods work by
changing the display attribute
of an element.
jQuery DOM
jQuery can select elements and classes in the DOM, traverse the DOM, get
and set elements and attributes of the DOM, and add or remove elements.
You can get the text, raw html, or value of a field with the methods text(),
html() and val().
You can access the attributes of an element with the method attr(label)
You can modify elements with text(newText), html(newHTML) and
val(newVal)
You can modify the attributes of an element with the method
attr(label,new value)
You can append, prepend, insert before and after with the functions
append, prepend before and after.
jQuery Filters
Using selectors, ids, names, and the DOM structure you can selector a
number of elements.
jQuery can also filter results, tables, lists and paragraphs:
Message Passing in Javascript
So far the javascript we have seen responds to local events in the browser,
such as users clicking buttons, pages loading, mouse movements etc.
However, we often want to respond to to remote events, such as someone
sending you a message, liking a post etc.
We also may want to dynamically respond to a local event using global
information: if a user enters the 1
st
of April as a prefered appointment date,
then we would like to immediately show them the available appointments.
We could send the date to the server, have the server rebuild the page and
send the entire page back, but we only required a few bytes of data.
AJAX vs WebSockets
There are several technologies to solve these problems
AJAX stands for Asynchronous Javascript And XML (eXtensible Markup
Language), and is really an approach rather than a technology.
AJAX was coined in 2005 by Jesse James Garrett, using asynchrous http
requests to a remote server and receiving XML data which could be parsed
using javascript and dyanmically update a webpage, using the DOM.
Each AJAX request is a single http protocol exchange, and is done
asynchronously, so that waiting for a response does not freeze the
environment.
The server will send the response as a data object (XML or JSON), which
can then be factored into the current page.
Websockets (2011) maintain an open two way connection between a
program running on a broswer, and a server, allowing the continual
exchange of data.
We will focus on AJAX for now, as it is the more fundamental technology.
Asynchrony
When we make a request to a service in javascript, we do not know when, if
ever the server will respond.
Javascript is single threaded, so it must execute each statement in order.
The environment Javascript runs in is not single threaded, so we can write a
function, with a function as a parameter, which will be executed when and if
the server responds.
Object.asyncFn(parameters, callbackFunction)
The callback function takes parameters, for errors or the response
generated, and executes them.
XML vs JSON
For a javascript function to communicate directly with a server, we require a
universal format to transmit data. The two most common forms are XML and
JSON.
XML is eXtensible Markup Langauage and is similar in form to HTML. All
data is contained in a tree of named tags. It is designed to be as general as
possible, it only contains data and does not execute, and is favoured by
academics.
JSON is JavaScript Object Notation and stores data in the syntax of
javascript: specifically the structural object declaration required to create the
object instance representing the data
JSON is more succinct and can contain arrays, but should not include
functions. Both XML and JSON are interpretted by parsers (JSON.parse)
Client Server Architecture
When Javascript running in the browser requires a service running on a
server, we are using a client-server-architecture.
The client sends a request to the server, the server recieves the request,
formulates and sends a response, and then forgets every thing about the
exchange (stateless).
l In the HTTP protocol, requests
have a specific form , specifying
the method (GET, POST,
UPDATE, DELETE) and URL,
come with a header and a
message body.
l A response reports the status (200
OK, 404 file not found), has a
header and a message body.
XMLHTTP requests
Modern browsers have an XMLHTTP request object to handle requests to,
and responses from a remote server.
The object is initialised, and then opens a connection to a server. The send
method sends the request to the server, and when the server responds, the
status and response can be accessed as properties.
Browsers only handle GET and POST requests.
HTTP requests continued
Requests maybe either GET or POST. Http allows other request methods
(DELETE, PUT) but these are not implemented by most browsers.
A GET request is used to retrieve data from a server, such as loading a
webpage, and a POST request is used to send data to a server, such as
submitting a form.
All requests should be done asynchronously so they do not block other
scripts running.
An asynchronous request has a readystate property describing the progress
of the request, and an onreadystatechange callback function, that is
executed when the readystate changes.
HTTP responses
The request changes state when the server responds, and the response is
accessibile as a property of the request (responseText or responseXML)
l As with the request, the
response has a status, the
status text, and a header,
which is a set of value key
pairs.
l The header can be used to
set parameters and cookies
etc.
l It is accessible via the
getResponseHeader
function
HTTP response codes
jQuery and AJAX
We can build XMLRequest objects directly, but jQuery provides some basic
functionality for us, and pairs it directly with the DOM.
The load function will send a GET request to a url, and load the data directly
into an HTML element
The get function will send a GET request to a url, and passes the data to a
callback function.
The post function will send a POST request, with data to a url and passes
the response to a callback function.
AJAX Callbacks
The following is a sequence diagram for an AJAX request
Example
Single Page Applications
Single Page Applications have the browser/client do the heavy lifting in a
web application: The server just provides the data while the client does the
logic and rendering
Application Architectures
Pros and Cons
Pros
Less load on the server, able to respond to more clients.
A more responsive client. No need to wait for server responses.
Genuine separation between content and presentation.
Cons
Longer load time, first up. A lot of JS has to be transferred.
SEO can be a problem. Robots won’t crawl js.
Navigation can be an issue.
To use AJAX or build single
page applications, we need to
be able to configure the server
to handle different requests.
So next lecture we’ll move on
to looking at the back end.