34
CSCI 6962: Server-side Design and Programming Introduction to AJAX

CSCI 6962: Server-side Design and Programming Introduction to AJAX

Embed Size (px)

Citation preview

Page 1: CSCI 6962: Server-side Design and Programming Introduction to AJAX

CSCI 6962: Server-side Design and Programming

Introduction to AJAX

Page 2: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Client/Server Model

• Response is entire web page• Very inefficient

– High network costs– Must be loaded into browser and rendered

• Problem:Browser itself cannot get any data from server without requesting entire page

Request

Client ServerResponse

LargeDocument

Page 3: CSCI 6962: Server-side Design and Programming Introduction to AJAX

AJAX Model

• Based on JavaScript running in browser– JavaScript code sends data to server, reads response– Response is simple data instead of entire page – Modifies page without re-rendering it completely

– AJAX: Asynchronous JavaScript and XML

Request

Web Page

Server

ResponseJavaScript

SmallData

Page 4: CSCI 6962: Server-side Design and Programming Introduction to AJAX

XMLHttpRequest Object

• XMLHttpRequest object acts as “link” to server– Sends request to given URL (including “form data”)– Allows access to status of request– Acts as reference to data sent back from server as

response

ServerJavaScript in Browser

XMLHttpRequest

Page 5: CSCI 6962: Server-side Design and Programming Introduction to AJAX

XMLHttpRequest Object

• XMLHttpRequest object represented differently on different browsers– Microsoft browsers represent as ActiveX– Other browsers support directly

• Must use “browser safe” JavaScript to create– Provide method to check capabilities and return object– Place declaration of XMLHttpRequest object directly in

JavaScript so object created automatically

Page 6: CSCI 6962: Server-side Design and Programming Introduction to AJAX

XMLHttpRequest Object

Will use this object in code

Page 7: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Example

• “Greeting” example– Reads name from text element– Sends to getGreeting servlet– Reads response– Displays in another text element

username=John

Text element

getGreeting

Server

JavaScriptHello John!

Page 8: CSCI 6962: Server-side Design and Programming Introduction to AJAX

JavaScript Page Structure

Button contains onClick() call to JavaScript greet() function

Page 9: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Opening Link to Server

• Syntax:request.open(method, URL, asynchronous);

XMLHttpRequest object created previously

GET or POST (usually POST)

true if asynchronous, false otherwise

The URL of the server, including the servlet name and any parameters

Page 10: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Adding Parameters to URL

• Data passed to server in form of requesthttp://domain/servletname?name=value&name=value&…

• Extract information from form (using JavaScript/DOM)• Append to URL to pass to server• Open that URL

URL Parameters appended

form.username.value

Page 11: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Adding Parameters to URL

Form name = “form”Field name = “username”

Extract the value of the username field of the form form

Append to request in name=value format

Page 12: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Sending Request/Receiving Response

• Send request to server:requestObject.send();

• Get response back from server as string:result = requestObject.responseText;

• Note: These commands must be in JavaScript try/catch

block in case no access to server

Page 13: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Manipulating Page• Use response to then manipulate page using JavaScript/

Document Object Model– Form element values– Document properties– Inserting new content…

Page 14: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Creating Content at the Server• Create servlet to handle request

– Gets data from request as before• Writes result to response object

– Create printWriter to response object using getWriter() – Write string to printWriter using print(String) method

Page 15: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Asynchronous Access• Getting response from server may take time

– Slow network access, lengthy response …• Continue with other tasks while waiting for response

– Spawn separate asynchronous process to handle response when it arrives

Get information from formOpen request to serverSend request

Continue other tasks(user interface, animation,etc.)

Wait for responseWhen response received, handle it (possibly changing page

Page 16: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Asynchronous Access

• Set asynchronous parameter to true in open• request.onreadystatechange

defines function to be called by asynchronous process

request.onreadystatechange = functionName

Send requestrequest.onreadystatechange = functionName

Continue other tasks(user interface, animation,etc.)

function functionName(){ Wait for response When response received, handle it }

Page 17: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Asynchronous Access

Page 18: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Status Checking

• Can track progress of response– Keep user up to data on status

request.readystate– Returns number indicating status of request

1 (loading) Request object created, but send method not called 2 (loaded) send method called, but response not yet available 3 (interactive) Some data received, and responseText will give

current partial results 4 (completed) All data received

Page 19: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Status Checking

Display message while waiting

Display response when loaded

Page 20: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Validation

• Problem: Validation costly in client/server model– Single error requires reload of entire page

• AJAX solution:– Use AJAX to send form data to server for validation– Receive any error messages as response– Submit form only if no errors

AJAX in browser

Server Validation servlet

Next page JSP

form data

errors

form submission

next page

Page 21: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Validation

• Client-side validation– Form can call function when SUBMIT button pressed

<form action = “nextPage” onSubmit = return validateFunction()>

– If function returns false, form not submitted

function validateFunction() { validate form data if (form valid) return true; else return false;}

Page 22: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Validation

• Validation outline using AJAX:function validate() {

var ok = true; // Any errors yet?for (all elements on form we must validate) { append form data to URL send request to validation servlet for that data response = request.responseText; if (response != “”) { ok = false; display error message in response } }

return ok;}

Page 23: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Validation

Must validate quantity entered by user

So call validateQuantitybefore form submitted

Page 24: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Validation

If no errors, return empty string

Do validation checks and create appropriate error message

Send message back to client

Page 25: CSCI 6962: Server-side Design and Programming Introduction to AJAX

ValidationGet quantity from form and submit to servlet

If no error message returned, return true (allows form submit)

Otherwise, display error message and return false (prevents form submit)

Page 26: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Timed Events

• Appearance: “Continuous feed” from server– Form field regularly updated by server

• AJAX Implementation:– Timer in JavaScript calls function at regular intervals– Function calls server-side servlet for current data– Displays current data on form

Page 27: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Timer Events

• Simple example: Server returns random number every time called by a client

Page 28: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Timer Events

• Create timer object in JavaScript• Attach timer to JavaScript function:window.setInterval(functionName, interval);

• Initialize inside function called when page loadedfunction intitializerFunction() { window.setInterval(functionName, interval);}…<body onLoad = “initializerFunction()”>

Function to call at regular intervals

Interval in miliseconds

Page 29: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Timer Events

Field where “feed” displayed

startTimer called when page loaded

readFeed called every second (1000 ms)

timer object declared globally

Page 30: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Timer Events

• Servlet creates illusion of “real-time” data– Get input from sensors, etc. at regular intervals– Based on data submitted asynchronously by other users

(online gaming, etc.)

AJAX in browser

Server Servlet

Game database

request data about state of game

moves change game state database

game state

Other players

Other players

Page 31: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Handling Lack of JavaScript

• Client browser must have JavaScript enabled for AJAX to work– Not always true (mobile browsers, etc.)

• Must still give some response if no AJAX– Submit form data using standard client-server

model– Send entire page back as response

Page 32: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Handling Lack of JavaScript

• Create a “backup” page on server to call if AJAX not supported:

Page 33: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Handling Lack of JavaScript

• Call that page when form submitted as action• Also call JavaScript AJAX function using onSubmit (as

in validation example)– Button must now be type=“submit”

Page 34: CSCI 6962: Server-side Design and Programming Introduction to AJAX

Handling Lack of JavaScript

• JavaScript function onSubmit() calls returns false– If JavaScript enable, server call prevented– Otherwise, server call made by default