http://www.dcs.bbk.ac.uk/news/
into the address bar
of a browserwww.dcs.bbk.ac.uk
on port 80/news/
method URL-path HTTP-version (request-line) headers (0 or more lines) <blank line> (CRLF) message-body (only if aPOST
orPUT
method)
GET
: request document named by URL-path
HEAD
: return only header information of
URL-path
(e.g., test for validity, recent modification)POST
: submit information to entity on server given by
URL-path
PUT
: server will replace entity given by
URL-path
GET /index.html HTTP/1.0
URL-path
includes optional query string
or fragment identifier (anchor)HTTP-version status-code reason-phrase (status-line) headers (0 or more lines) <blank line> (CRLF) message-body
HTTP/1.0 200 OK
message-body
if request
successful; reason-phrase
states why
unsuccessfulStatus Code | Reason Phrase |
---|---|
200 | OK |
401 | Unauthorized |
404 | Not Found |
500 | Internal Server Error |
field: value
Host:
the domain name (and port) of the server;
required in every request; allows server to
differentiate requests for multiple hosts with same IP addressUser-Agent:
information about the client program (type,
version)Accept:
formats acceptable to the client,
given using MIME typesServer
: name and version of serverContent-Type
: the (MIME) media type of the resource being returnedContent-Length
: size of message body in bytesLast-Modified
: date and time when entity was last
modifiedMachine responses are this colour
below:
Peter-Woods-MacBook-Pro:~ ptw$ telnet www.dcs.bbk.ac.uk 80 Trying 193.61.29.21... Connected to www.dcs.bbk.ac.uk. Escape character is '^]'. GET / HTTP/1.0 HTTP/1.1 200 OK Date: Fri, 18 Nov 2011 17:44:06 GMT Server: Apache/2.2.16 (Unix) mod_ssl/2.2.16 OpenSSL/0.9.8o DAV/2 SVN/1.6.5 mod_fcgid/2.3.6 mod_perl/2.0.4 Perl/v5.8.4 Connection: close Content-Type: text/html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Computer Science and Information Systems Birkbeck University of London</title> ... </body> </html> Connection closed by foreign host. Peter-Woods-MacBook-Pro:~ ptw$
<form action="http://titan.dcs.bbk.ac.uk/~ptw/teaching/IWT/server/www-inventor.php" method="GET"> <label for="www-inventor">Who invented the WWW (surname only)?</label> <input type="text" id="www-inventor" name="inventor" /> <input type="submit" value="Submit answer" /> <input type="reset" value="Erase answer" /> </form>
action
gives URI of PHP script (see later) to runmethod
used is GET
name
attribute?inventor=Berners-Lee
, e.g., is added to URL-pathform
element has
action
attribute whose value is the URI for processing
agentmethod
attribute whose value specifies the HTTP method to use
for sending data: GET
or POST
name=value
pairs
name
is the value of the name
attribute of an input controlvalue
is the value of the corresponding value
attribute or is entered by the username=value
pairs are separated by &
charactersGET
, name=value
pairs form the URI query stringPOST
, name=value
pairs form the message bodySet-Cookie: sessionid=724A3B616C0D89B3B521C70612
Cookie: sessionid=724A3B616C0D89B3B521C70612
web.js
contain the following Javascript code:
var http = require('http'); var fs = require('fs'); var port = 8080; function process_request(request, response) { response.writeHead(200); response.end(fs.readFileSync(__dirname + request.url)); } var server = http.createServer(process_request); server.listen(port); console.log('Listening on port ' + port);
http
is the web server modulefs
is the file system modulecreateServer
launches a web server,
and is passed a function to call when requests arriveprocess_request
takes the request and produces a responserequest.url
)web.js
,
we enter the following at the command line
node web.js
Listening on port 8080
curl -i http://localhost:8080/test.html(
curl
is a Unix command for retrieving URLs from the command line; -i
includes headers)HTTP/1.1 200 OK Date: Mon, 02 Mar 2020 11:35:04 GMT Connection: keep-alive Transfer-Encoding: chunked <html> ... contents of test.html ... </html>
<?php
and
?>
delimiters for PHP code<html> <head><title>WWW Inventor</title></head> <body> <h1> <?php if ($_GET['inventor'] == "Berners-Lee") echo "Congratulations, you answered correctly."; else echo "Sorry, the correct answer is Berners-Lee."; ?> </h1> </body> </html>
$
$_GET
is an associative array providing access
to the values of name=value
pairs in the query string$_GET['inventor']
gets value of
inventor
parameter in query stringecho
or print
<dictionary> <acronym>AJAX</acronym> ... <acronym>XSLT</acronym> </dictionary>
<xsl:template match="/dictionary"> ... <ul> <xsl:for-each select="acronym"> <li> <xsl:value-of select="."/> </li> </xsl:for-each </ul> ... </xsl:template>
acronyms.php
is:
<?php $xmlDoc = new DomDocument(); $xmlDoc->load("acronyms.xml"); $xslDoc = new DomDocument(); $xslDoc->load("acronyms.xsl"); $processor = new XSLTProcessor(); $xslDoc = $processor->importStylesheet($xslDoc); $htmlDoc = $processor->transformToDoc($xmlDoc); print $htmlDoc->saveXML(); ?>
DomDocument
and
XSLTProcessor
are PHP objectsload
,
importStylesheet
and
transformToDoc
are PHP methodstransformToDoc
uses
the associated stylesheet to return an HTML/XML documentsaveXML
method
converts a DOM tree to a stringhttps://www.nobelprize.org
http://api.nobelprize.org/v1/prize.json?year=1991
year
: year in which prizes were awardedyearTo
: ending year for a range of years (year
required)category
: one of the 6 categoriesnumberOfLaureates
: filter prizes by number of winners sharing the prizeGET
, POST
, PUT
, DELETE
GET
will retrieve a resourcePOST
will create a new resourcePUT
will overwrite an existing resourceDELETE
will delete a resourcename
of the textbox in the form is year
action
value is http://titan.dcs.bbk.ac.uk/~ptw/teaching/IWT/server/nobel-year.php
<html> <body> <h1>Nobel Prize Winners</h1> <?php $year = $_GET['year']; if ($year >= 1901 && $year <= 2017) { $url = 'http://api.nobelprize.org/v1/prize.json?year=' . $year; $string = file_get_contents($url); # Read the JSON output into an associative array $result = json_decode($string, true); print "<p>In $year, the prizes were awarded as follows:</p><ul>\n"; ... # see next slide print "</ul>"; } else { print "<p>Year value out of range; years range from 1901 to 2017</p>"; } ?> </body> </html>
$_GET
(on slide 15).
file_get_contents
returns file contents as a stringjson_decode
with second parameter set to true
returns JSON string as an associative array$year
, inside strings
delimited by double quotes are dereferenced (but not for single quotes)returned JSON data is as follows (for year
1991):
{"prizes": [ {"year":"1991", "category":"physics", "laureates":[ {"id":"141", "firstname":"Pierre-Gilles", "surname":"de Gennes", "motivation":"...", "share":"1"}]}, {"year":"1991", "category":"chemistry", "laureates":[ {"id":"276", "firstname":"Richard R.", "surname":"Ernst", "motivation":"...", "share":"1"}]}, {"year":"1991", "category":"medicine", "laureates":[ {"id":"444", "firstname":"Erwin", "surname":"Neher", "motivation":"...", "share":"2"}, {"id":"445", "firstname":"Bert", "surname":"Sakmann", "motivation":"...", "share":"2"}]}, {"year":"1991", "category":"literature", "laureates":[ {"id":"668", "firstname":"Nadine", "surname":"Gordimer", "motivation":"...", "share":"1"}]}, {"year":"1991", "category":"peace", "laureates":[ {"id":"553", "firstname":"Aung San Suu Kyi", "motivation":"...", "share":"1", "surname":""}]}, {"year":"1991", "category":"economics", "laureates":[ {"id":"707", "firstname":"Ronald H.", "surname":"Coase", "motivation":"...", "share":"1"}]} ] }
$result
contains the JSON data as an associative array# Find out how many prizes are listed $num_prizes = count($result['prizes']); for ($i = 0; $i < $num_prizes; $i++) { # Print out the category $cat = $result['prizes'][$i]['category']; print "<li>in $cat to <ul>\n"; # Find out how many winners in this category $num_winners = count($result['prizes'][$i]['laureates']); for ($j = 0; $j < $num_winners; $j++) { # Print out the names $firstname = $result['prizes'][$i]['laureates'][$j]['firstname']; $surname = $result['prizes'][$i]['laureates'][$j]['surname']; print "<li>$firstname $surname </li>\n"; } print "</ul></li>\n"; }
count
counts number of elements in an arrayXMLHttpRequest
object (built in to browsers)
get
method: $.get( url [, data ] [, success ] [, dataType ] )
is shorthand for:
$.ajax({ url: url, data: data, success: success, dataType: dataType });both return a
jqXHR
object (a superset of XMLHttpRequest
)
XMLHttpRequest
objectXMLHttpRequest
object (XHR for short) is a WHATWG
specification
var xhr = new XMLHttpRequest(); xhr.open("GET", url, false); xhr.send(null); var xmldoc = xhr.responseXML;
XMLHttpRequest
object
open
method sets up an HTTP request:
GET
in this case)false
means synchronous: interpreter waits for response
before continuing (not recommended)
send
method sends the HTTP request
to the server; content is null for GET
responseXML
property makes response available as XML
(responseText
can also be used)open
are asynchronous,
we need to specify an event handlerXHR
has a readyState
property
and an onreadystatechange
eventreadyState
are:
readyState
changes:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function;
...
Origin
in the requestAccess-Control-Allow-Origin
in the responseOrigin
specifies the domain name origin of the requestAccess-Control-Allow-Origin
value can be *
for any origin, or the single origin in the requestif($_SERVER['HTTP_ORIGIN'] == "http://www.dcs.bbk.ac.uk") { header('Access-Control-Allow-Origin: http://www.dcs.bbk.ac.uk'); ... }
$_SERVER
is an associative array of values available from the serverHTTP_ORIGIN
gives the value of the Origin:
headerheader()
function sets an HTTP header to be sent with the response
<form>
<input type="text" id="txtSearch" name="txtSearch"
onkeyup="searchSuggest();" autocomplete="off" />
<div id="search_suggest">
</div>
</form>
id="txtSearch"
searchSuggest()
(next slide)
is called in response to an onkeyup
eventautocomplete="off"
turns off browser default to suggest recently entered datadiv
with id="search_suggest"
is where suggestions will appearvar searchReq = getXmlHttpRequestObject(); function searchSuggest() { if (searchReq.readyState == 4 || searchReq.readyState == 0) { var str = escape(document.getElementById('txtSearch').value); searchReq.open("GET", 'searchSuggest.php?search=' + str, true); searchReq.onreadystatechange = handleSearchSuggest; searchReq.send(null); } }
getXmlHttpRequestObject
just returns an XMLHttpRequest objectid="txtSearch"
open
are asynchronoushandleSearchSuggest
) when
readyState
changes<?php header("Content-Type: application/json; charset=utf-8"); ... $suggestions = array("Ajax","ASP","Javascript","JSP","XML","XPath","XSD","XSLT"); $result = array(); // Make sure that a value was sent. if (isset($_GET['search']) && $_GET['search'] != '') { $search = $_GET['search']; ... // see next slide } ?>
isset
function checks that a value is not NULL
$result
is an array
... foreach ($suggestions as $suggestion) { // Add each suggestion to the $result array if (strpos($suggestion,$search)===0) $result[] = $suggestion; } echo json_encode($result); ...
foreach
allows iteration through array
strpos
returns first position where
second argument is found in first argument, or FALSE
if not found
FALSE==0
is true in PHP, need to use strict comparison
===
to check types are equal too
$search
matches $suggestion
at 0'th position
$suggestion
to $result
array
$result
array as JSON using json_encode
//Called when the AJAX response is returned. function handleSearchSuggest() { if (searchReq.readyState == 4) { var ss = document.getElementById('search_suggest'); ss.innerHTML = ''; var str = JSON.parse(searchReq.responseText); // PTW modified for JSON // For loop to build list of suggestions goes here (next slide) } }
div
element under textbox in form has id="search_suggest"
responseText
since response is text (in JSON format)
JSON.parse()
parses JSON text, returning a JSON type
for
loop is on the next slide
... // Returned suggestions are in array str for(i=0; i < str.length; i++) { //Build our element string. This is cleaner using the DOM, //but IE doesn't support dynamically added attributes. var suggest = '<div onmouseover="javascript:suggestOver(this);" '; suggest += 'onmouseout="javascript:suggestOut(this);" '; suggest += 'onclick="javascript:setSearch(this.innerHTML);" '; suggest += 'class="suggest_link">' + str[i] + '</div>'; ss.innerHTML += suggest; } ...
div
element with
mouseover
,
mouseout
and
onclick
events
suggestOver
,
suggestOut
and
setSearch
are defined on next slide
//Mouse over function function suggestOver(div_value) { div_value.className = 'suggest_link_over'; } //Mouse out function function suggestOut(div_value) { div_value.className = 'suggest_link'; } //Click function function setSearch(value) { document.getElementById('txtSearch').value = value; document.getElementById('search_suggest').innerHTML = ''; }
suggest_link_over
is a CSS class value which highlights the suggestion
suggest_link
unhighlights the suggestion
setSearch()
enters the value in the search box and clears the suggestions
ajax_search.js
and
the CSS file suggest.css
getElementsByTagName
method which returns a
DOMNodeList
. A DOMNodeList
has a length
property and an item
method which takes an index value and returns
a DOMNode
. A DOMNode
has
firstChild
and nodeValue
properties (see the
PHP DOMDocument Class
and links from there).
ajax_search.js
for the Google Suggest lookalike so that it uses jQuery.
get
methodHTTP is covered briefly in Section 4.6 of [Comer]. Section 7.3 of [Tanenbaum] covers HTML forms and HTTP, and mentions CGI and PHP. Servlets are covered in Chapter 9 and JSP in Chapter 10 of [Moller and Schwartzbach]. Server-side processing of XML using PHP (and VB.NET) is covered in Chapters 11 (12) and 13 in [Jacobs]. AJAX is covered in Chapter 9 in [Jacobs]. It is also mentioned in Section 7.3.3 of [Tanenbaum].