Introduction To AJAX

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 43

Introduction To AJAX

Asynchronous JavaScript and XML

Course Outline
Day 1 I. Introduction II. Getting Started Day 2 III. Using Dynamic Content IV. Applications

I. Introduction

I. Introduction
1. User Experience on the Web

2. What is AJAX?
3. How AJAX Works 4. AJAX Drawbacks 5. Development Tools

1. User Experience on the Web


HTTP is a synchronous protocol: Request, Wait for

response.
A web application is completely idle during load

time (no user interaction)


Early 90s web applications where always

synchronous which lead to very poor UX (User eXperience)

1. User Experience on the Web


Asynchronous communication in web pages was first

introduced in Java Applets (mid 90s)


communication methods

Macromedia Flash also offered asynchronous

Applications built with such technologies resemble

desktop applications in many ways: responsiveness, instant feedback, no idle time


Such applications are called Rich Internet

Applications (RIA)

1. User Experience on the Web


JS has enough capabilities to build rich UIs on the web Problem: not possible to communicate the server

without re-loading the entire page


An asynchronous communication capability was added

to JavaScript in 1999: the XMLHttpRequest object.

Some web applications started using it to build RIAs.

e.g. Outlook Web Access and Gmail (Early 2000s).

In 2005, this technique was called AJAX

2. What is AJAX?
Asynchronous JavaScript And XML A group of web development techniques used to create asynchronous web applications

Not a single technology. An HTML-JS-CSS combo Despite the name, XML is not necessarily needed

3. How AJAX Works

3. How AJAX Works


User generates an event

XMLHttpRequest object is created by interaction function


Callback function is prepared and linked to the request

Request is configured and calls server side script


Upon response, callback is triggered and updates area of page using DOM

4. AJAX Drawbacks
AJAX requests are not saved in browser history. Pages with AJAX-loaded content are not easily

bookmarked in their current state


A fairly complex workaround exists using URL

fragment identifiers (# section of URL). Requires backend changes as well

Solvable using an HTML5 API that communicates with

browser history engine

4. AJAX Drawbacks
AJAX-loaded content is not accessible to search

engines
The callback-based programming style can lead to

more complex code thats hard to trace and/or debug

5. Development Tools
A good text editor: Notepad++, gedit or vim have good syntax highlighting and proper indentation Netbeans and Aptana have powerful auto-complete features for JS, HTML and CSS A modern browser with JS console/debugger: Google Chrome (built-in console) Mozilla Firefox (+Firebug add-on)

II. Getting Started

Getting Started
1. XMLHttpRequest Javascript Object

2. First AJAX Request


3. Basic DOM Operations 4. Lab Exercise
1. 2. First AJAX Username validation

1. XMLHttpRequest Object
Methods
open(mode, url, asynchronous)
send(params) abort() getAllResponseHeaders() getResponseHeader(header)

Properties
readyState status responseText responseXml

onreadystatechange

1. XMLHttpRequest Object
readyState

integer, values range 0 4 according to request state


0 : not initialized 1 : connection established 2 : request received 3 : processing request 4 : request finished and repsponse ready

status

HTTP status code, e.g. 200, 404, 403, etc

1. XMLHttpRequest Object
responseText

response data as plain text string


responseXML

response data as XML data


onreadystatechange

stores a function to be called automatically every time the readyState value changes

1. XMLHttpRequest Object
open(method, url, asynch, user, pass)

creates a connection to specified URL preparing the request to be sent


method: HTTP method (GET / POST) url: url to the server-side script or resource asynch (optional): when true (default) request is asynchronous, when false request is synchronous user (optional): username for HTTP Authentication pass (optional): password for HTTP Authentication

1. XMLHttpRequest Object
send(params)

sends the request off to the server


params: string containing POST parameters, set to null in case of GET

abort()

completely aborts/cancels the request


getAllResponseHeaders

returns all headers of the response as a hash (map)


getResponseHeader(headerName)

returns specific header such as User-Agent


headerName: name of header to retrieve

2. First AJAX Request


1. Create XMLHttpRequestObject
// supported: IE7+, FireFox, Chrome, Safari and Opera request = new XMLHttpRequest(); // for IE5, IE6 (obsolete) request = new ActiveXObject(Microsoft.XMLHTTP);

2. First AJAX Request


2. Prepare callback function
request.onreadystatechange = function() {
if (request.readyState == 4) { // response ready, time to update DOM } else { // not ready, show progress animation } };

2. First AJAX Request


3. Open connection and send
// open connection to my server-side script request.open(GET, http://mydomain/script.php, true);
// send off the request request.send(null);

2. First AJAX Request


<form method=POST name=myform action=> <input type=button value=Fire Request onclick=handleUserAction() /> <input type=text name=res /> </form>

2. First AJAX Request


<script type=text/javascript> var xhr = null function handleUserAction() { xhr = new XMLHttpRequest(); xhr.onreadystatechange = xhrCallback; xhr.open(GET, data.txt, true); xhr.send(null); } function xhrCallback() { if (xhr.readyState == 4) { document.myform.res.value = xhr.responseText } else { document.myform.res.value = err: + xhr.status; } } </script>

3. Basic DOM Operations


We need to validate the username and tell the user

the result of the validation as shown below:

3. Basic DOM Operations

Server-side PHP code


<?php if ($_GET[username] == Mohsen) { echo valid; } else { echo invalid; } ?>

3. Basic DOM Operations

Client-side JavaScript code


function handleUserAction() { // read user input from form var uname = document.getElementById(uname).value; // prepare request to server-side php and send it // with username as parameter ... } function xhrCallback() { var validity = ; // change validity value based on server response ... // display result in text field document.getElementById(res).value = validity }

4. Lab Exercise
1. First AJAX

simply button will trigger AJAX request to the server, read data.txt and display response in text field

4. Lab Exercise
2. Username validation

we need to validate the username (on the server) and display the result to the user

III. Using Dynamic Content

III. Using Dynamic Content


1. Parsing the Response Introducing JSON 2. DOM Manipulations 3. Sending Post Parameters

4. Lab Exercise

1. Parsing the response


In many applications, we need a large, complex

response from the server.


Examples: List of search results or a list of

comments (including name, photo, etc)

Response cannot be plain text, it needs to be: Logically Organized Easy to parse using JavaScript Both XML and JSON fit this criteria

1. Parsing the response


JSON is the format of choice form most web

developers these days JavaScript Object Notation A lightweight, language independent, data interchange format. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects.

1. Parsing the response


Sample JSON output (status message + user

comments)
{ status: Jan 25 FTW!, time: Feb 11, 2011 @ 22:00, likes: [Mahmoud Samy, Samir Bahgat, Mohsen Abdallah], comments: [ {user:Sara Ammar, text:Alriiiight!, likes:5}, {user:Mahmoud Samy, text:Go Jan25!!!, likes:4} ] }

1. Parsing the response


Supported data types { } Object : list of keys and values [ ] Array : list of values (or objects) Boolean : true or false Number : double precision supported String : double-quoted text JSON format matches JavaScripts object structure

exactly, so its vey easy to parse in JavaScript

1. Parsing the response


How to parse the previous response in JS
var statusObj = JSON.parse(xhr.responseText); // response is now parsed into JS objects and ready to use // alert the status message alert(statusObj.status); // alert list of people who like this var likes = for(var i = 0; statusObj.likes.length; i++) { likes += statusObj.likes[i] + , ; } alert(likes);

// alert name of first commentor alert(statusObj.comments[0].user);

2. DOM Manipulations
DOM review document.createElement(tagName) document.createTextNode(text) <element>.appendChild(childNode) <element>.getAttribute(name) <element>.setAttribute(name, value) <element>.insertBefore(newNode, targetNode) <element>.removeAttribute(name) <element>.removeChild(childNode) <element>.replaceChild(newNode, oldNode) <element>.innerHTML

2. DOM Manipulations
DOM Example on adding comments
var commentsDiv = document.getElementById(commentsContainter); for (var i = 0; i < statusObj.comments.length; i++) { var commentHTML = statusObj.comments[i].user + <br/>; commentHTML += statusObj.comments[i].text;

var cDiv = document.createElement(div); cDiv.style.backgroundColor = #e7e7e7; cDiv.innerHTML = commentHTML;


commentsDiv.appendChild(cDiv); }

3. Sending POST Parameters


Sending POST parameters requires sending a

header specifying data format to the web server


xhr.open(POST, http://localhost/register.php, true); var userParams = + + + username= + username &password= + password &email= + email &fullName= + fullName;

// this header is required to specify parameter format xhr.setRequestHeader("Content-Type","application/x-www-formurlencoded;); xhr.send(userParams);

4. Lab Exercise
1. Loading Lists

use API to dynamically load intakes, departments in each intake and students in each department

4. Lab Exercise
A PHP API will be provided for you to use Sample call to get list of intakes:

4. Lab Exercise

Sample call to get list of departments:

Sample call to get list of students

You might also like