Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
CHAPTER 10 - AJAX
10 - 1
Traditional web interaction
http://domain.com Google
HTTP request
HTTP request to server
time
activity while it waits for user waiting
the server to provide the server
document
http://domain.com Google
HTTP response
- When the response arrives, (complete document)
10 - 2
Motivation
10 - 3
AJAX
10 - 4
AJAX interaction
initial request
http://domain.com
Web Page Title
Google
complete document
web
time
server
10 - 5
AJAX interaction
initial request
http://domain.com
Web Page Title
Google
complete document
web
time
interaction #1
server
10 - 6
AJAX interaction
initial request
http://domain.com
Web Page Title
Google
complete document
update #1
web
time
interaction #1
partial update #1
server
10 - 7
AJAX interaction
initial request
http://domain.com
Web Page Title
Google
complete document
update #1
web
time
interaction #1
partial update #1
server
interaction #2
10 - 8
AJAX interaction
initial request
http://domain.com
Web Page Title
Google
complete document
update #1
web
time
interaction #1
update
partial update #1
server
#2
interaction #2
partial update #2
10 - 9
Note that responses are asynchronous
initial request
http://domain.com
Web Page Title
Google
complete document
update #1
web
time
interaction #1
update server
#2
interaction #2
partial update #2
partial update #1 The response to request #1 might arrive
after #2, even though it was made earlier
10 - 10
Where to use AJAX?
10 - 11
Where to use AJAX?
10 - 12
Four main parts
10 - 13
Example walkthrough
https://github.com/kbalog/web-programming/tree/master/
examples/ajax/zipcode
10 - 14
Example
10 - 15
1. Initial HTML document
zipcode.html
<input type="text" name="postcode" onkeyup="getPlace(this.value);"/>
10 - 16
2. Request phase
10 - 18
4. Receiver phase
10 - 19
Example walkthrough #2
https://github.com/kbalog/web-programming/tree/master/
examples/ajax/license
10 - 20
Example #2
10 - 21
Example #2
- The client updates part of the page (i.e., the DOM) with the
received snippet
10 - 22
1. Initial HTML document
- I.e., whenever the user presses a key in the name or license fields
license.html
<input type="text" name="name" id="name" onkeyup="checkLicense();" />
10 - 23
2. Request phase
license.js
function checkLicense() {
[…]
/* send the request using POST */
xhr.open("POST", "/check_license", true);
/* To POST data like an HTML form, add an HTTP header */
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
/* variables go in the request body */
xhr.send("name=" + name + "&license=" + license);
[…]
}
10 - 24
3. Response document
app.py
@app.route("/check_license", methods=["POST"])
def check_license():
VALID_LICENSES = {…}
name = request.form.get("name", None)
license = request.form.get("license", None)
# check if name and license match
if name and license:
if VALID_LICENSES.get(name, None) == license:
return "<img src='/static/images/yes.png' /> Valid license key"
else:
return "<img src='/static/images/no.png' />
Invalid license key for {}".format(name)
return ""
10 - 25
4. Receiver phase
10 - 26
Exercises #1, #1b
https://github.com/kbalog/web-programming/tree/master/
exercises/ajax
10 - 27
What can be the response document?
- HTML snippet
- Data as "object"
- Both the client and the server need to speak the same language, i.e.,
how to encode and decode the object
10 - 28
JSON
- Language independent
- Two structures
10 - 29
JSON
- Values can be
10 - 30
Example JSON
{
"name":"John Smith",
"age":32,
"married":true,
"interests":[1,2,3],
"other":{
"city":"Stavanger",
"postcode":4041
}
}
10 - 31
JSON with Python
examples/ajax/json/json_python.py
- json.dumps(data)
- returns JSON representation of the data
- json.loads(json_value)
- decodes a JSON value
- json.dumps() and json.loads() work with strings
10 - 32
JSON with JavaScript
examples/ajax/json/json_js.html
- JSON.stringify(value)
- returns JSON representation of a value (encode)
- JSON.parse(json)
- parses a JSON value into a JavaScript object (decode)
10 - 33
Exercise #2
https://github.com/kbalog/web-programming/tree/master/
exercises/ajax
10 - 34
Example
https://github.com/kbalog/web-programming/tree/master/
examples/ajax/loading
10 - 35
Indicating waiting
- An animated gif is
displayed until the
response arrives
10 - 36
AJAX in jQuery
10 - 37
AJAX controls
- load() method
- replaces the HTML content of the matched elements with the content
returned from a remote file
- (does not work with form input fields!)
- Full reference:
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
10 - 38
$.ajax()
- $.ajax(params)
- where params is a settings map object
var params = {
type: "GET",
url: "requestUrl",
dataType: "text", // html, xml, json
success: successCallbackFunction,
error: errorCallbackFunction
};
10 - 39
$.get(), $.post()
- Full syntax:
- $.get(url,data,function(data,status,xhr),dataType)
- $.post(url,data,function(data,status,xhr),dataType)
- Where:
10 - 40
Example (zipcode) using JavaScript
examples/ajax/zipcode/
function getPlace(postcode) {
var xhr = new XMLHttpRequest();
/* register an embedded function as the handler */
xhr.onreadystatechange = function () {
/* readyState = 4 means that the response has been completed
* status = 200 indicates that the request was successfully completed */
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
document.getElementById("place").value = result;
}
};
/* send the request using GET */
xhr.open("GET", "/getplace?postcode=" + postcode, true);
xhr.send(null);
}
10 - 41
Example (zipcode) using jQuery
examples/jquery/zipcode2/
$(document).ready(function() {
$("input[name=postcode]").blur(function() {
$.get("/getplace", {postcode: $(this).val()}, function (data) {
$("#place").val(data);
});
});
});
10 - 42
load()
- Loads data from a server and puts the returned data into the
selected element
- $load(url,data,function(data,status,xhr))
- Where:
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
10 - 43
Exercises #3, #4
https://github.com/kbalog/web-programming/tree/master/
exercises/ajax
10 - 44