A browser sends an HTTP request to a server…
But a client-side script can also send a HTTP request
XMLHttpRequest objectsSummary of what your client-side script needs to do in order to send an HTTP request:
XMLHttpRequest examplelet request = new XMLHttpRequest();
request.addEventListener('readystatechange', handle_response, false);
request.open("GET", url, true);
request.setRequestHeader("User-Agent", "XMLHttpRequest");
request.setRequestHeader("Accept-Language", "en");
request.send(null);
request)
request.status: the status code sent back
by the serverrequest.getResponseHeader("…"): to
access the specified response header
request.getAllResponseHeaders(): to
access all response headers as an array
request.responseText: to access the
body of the server's response as a string
request.responseXML: to access the body
of the server's response as XML (inc. HTML)
function handle_response() {
// Check that the response has fully arrived
if ( request.readyState === 4 ) {
// Check the request was successful
if ( request.status === 200 ) {
// do whatever you want to do with
// request.responseText or request.responseXML
}
}
}
Ajax…
XMLHttpRequests), the DOM, HTML and CSS
What's the idea…
XMLHttpRequest to
fetch from the server just the content that has changed
let score = 0;which goes up by 1 for every 33ms that the player survives:
function draw() {
score = score + 1;
…
}
store_score.py will put the score into a database:
let request;
function stop() {
clearInterval(interval_id);
window.removeEventListener('keydown', activate);
window.removeEventListener('keyup', deactivate);
let url = 'store_score.py?score=' + score;
request = new XMLHttpRequest();
request.addEventListener('readystatechange', handle_response, false);
request.open('GET', url, true);
request.send(null);
}
function handle_response() {
// Check that the response has fully arrived
if ( request.readyState === 4 ) {
// Check the request was successful
if ( request.status === 200 ) {
if ( request.responseText.trim() === 'success' ) {
// score was successfully stored in database
} else {
// score was not successfully stored in database
}
}
}
}
store_score.py#!/usr/local/bin/python3
from cgitb import enable
enable()
from cgi import FieldStorage
from html import escape
import pymysql as db
print('Content-Type: text/plain')
print()
form_data = FieldStorage()
score = escape(form_data.getfirst('score', '').strip())
try:
connection = db.connect('localhost', 'userid', 'password', 'database_name')
cursor = connection.cursor(db.cursors.DictCursor)
cursor.execute("""INSERT …""", (score))
connection.commit()
print('success')
cursor.close()
connection.close()
except db.Error:
print('problem')
register.py from the lecture on
user authentication
check_name_available.js) will
XMLHttpRequest to the server,
asking it to run a Python program
(check_name_available.py)
register.py (modified)print("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Web Dev 2</title>
<script src="check_name_available.js" type="module"></script>
</head>
<body>
<form action="register.py" method="post">
<label for="username">User name: </label>
<input type="text" name="username" id="username" value="%s" />
<span id="checker"></span>
<label for="password1">Password: </label>
<input type="password" name="password1" id="password1" />
<label for="passwords2">Re-enter password: </label>
<input type="password" name="password2" id="password2" />
<input type="submit" value="Register" />
</form>
%s
</body>
</html>""" % (username, result))
check_name_available.py#!/usr/local/bin/python3
from cgitb import enable
enable()
from cgi import FieldStorage
from html import escape
import pymysql as db
print('Content-Type: text/plain')
print()
form_data = FieldStorage()
username = escape(form_data.getfirst('username', '').strip())
try:
connection = db.connect('localhost', 'userid', 'password', 'database_name')
cursor = connection.cursor(db.cursors.DictCursor)
cursor.execute("""SELECT * FROM users
WHERE username = %s""", (username))
if cursor.rowcount > 0:
print('in_use')
else:
print('available')
cursor.close()
connection.close()
except db.Error:
print('problem')
check_name_available.jslet username;
let checker;
let request;
document.addEventListener('DOMContentLoaded', init, false);
function init() {
username = document.querySelector('#username');
checker = document.querySelector('#checker');
username.addEventListener('keypress', set_link, false);
checker.addEventListener('click', check_name_available, false);
}
function set_link() {
checker.innerHTML = '<a href="#">Check name is available</a>';
}
function check_name_available() {
let url = 'check_name_available.py?username=' + username.value;
request = new XMLHttpRequest();
request.addEventListener('readystatechange', handle_response, false);
request.open('GET', url, true);
request.send(null);
}
function handle_response() {
// Check that the response has fully arrived
if ( request.readyState === 4 ) {
// Check the request was successful
if ( request.status === 200 ) {
if ( request.responseText.trim() === 'available' ) {
checker.innerHTML = 'Name available';
} else if ( request.responseText.trim() === 'in_use' ) {
checker.innerHTML = 'Name not available';
}
}
}
}