07AJAX
07AJAX
9
jQuery
l CSS manipulation
l Some utilities
• jQuery implements some useful effects, including hide, show, fade, slide
and animate.
• 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 dynamicallystrespond to a local event using global
information: if a user enters the 1 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
• 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)
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.