PHP and AJAX
Exchange data interface
AJAX
• What is AJAX ?
• AJAX stands for Asynchronous JavaScript and XML. AJAX is a new
technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
• Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
• With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
Bakker 2016
2
AJAX
• AJAX example
• XMLHttpRequest
• Send a Request To a Server
• Server response
• The onreadystatechange event
• ASP example
• PHP example
• XML example
AJAX
• XMLHttpRequest:
• Variabele -> XMLHttpRequest
• ajaxRequest = new ActiveXObject( "Microsoft.XMLHTTP“ )
• ajaxRequest.open( "GET", "ajax-example.php", true )
• ajaxRequest.send()
• ajaxRequest.onreadystatechange = function() { if(ajaxRequest.readyState == 4) {
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
Bakker 2016
4
PHP and AJAX Example
PHP and AJAX Example
Bakker 2016
6
PHP and AJAX Example
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' /> <br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()‘ value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
URL?variable1=value1;&variable2=value2;
PHP and AJAX Example table
CREATE TABLE `ajax_example` (
`name` varchar(50) NOT NULL,
`age` int(11) NOT NULL,
`sex` varchar(1) NOT NULL,
`wpm` int(11) NOT NULL,
PRIMARY KEY (`name`) )
Bakker 2016
8
PHP and AJAX Example
INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);
PHP and AJAX Example
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
// Internet Explorer Browsers try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong alert("Your browser broke!");
return false;
}
Bakker 2016
10
PHP and AJAX Example
<!DOCTYPE html>
<!-- Boek php basics hoofdstuk Ajax of XHTML -->
<html>
<body>
<script language="javascript" type="text/javascript">
<!-- //Browser Support Code function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) { try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong alert("Your browser broke!");
return false;
} } }
// Create a function that will receive data // sent from the server and will update // div section in the same page.
ajaxRequest.onreadystatechange = function() { if(ajaxRequest.readyState == 4) { var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
} }
// Now get the value from user and pass it to // server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ; queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
} //-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
PHP and AJAX Example
<?php
$dbhost = "localhost";
$dbuser = "ajax";
$dbpass = "ajax";
$dbname = "ajax";
//Connect to MySQL Server
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname" ,$dbuser, $dbpass);
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
//Execute query
$qry_result = $dbh->query($query);
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
$qres = $dbh->prepare($query);
$qres->execute();
while ( $row = $qres->fetch() ) {
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
Bakker 2016
12
XMLHttpRequest
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is
possible to update parts of a web page, without reloading
the whole page.
XMLHttpRequest
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new
ActiveXObject("Microsoft.XMLHTTP");
}
Bakker 2016
14
Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Send a Request To a Server
Example GET
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
Example POST
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
Bakker 2016
16
Server response
To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.
Property Description
responseText get the response data as a string
responseXML get the response data as XML data
Server response
The responseText Property
document.getElementById("demo").innerHTML = xhttp.responseText;
The responseXML Property
xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
Bakker 2016
18
Events : onreadystatechange
The onreadystatechange event
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object:
Events
Property Description
onreadystatechange Stores a function (or the name of a
function) to be called automatically each time the readyState property changes
readyState
Holds the status of the XMLHttpRequest.
Changes from 0 to 4:
0: request not initialized
1: server connection established 2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found
Bakker 2016
20
The onreadystatechange event
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
AJAX Database Example - ASP
function showCustomer(str) { var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
} };
xhttp.open("GET", "getcustomer.asp?q="+str, true);
xhttp.send();
}
Bakker 2016
22
AJAX Database Example - ASP
<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"
set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/datafolder/northwind.mdb")) set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn
response.write("<table>") do until rs.EOF
for each x in rs.Fields
response.write("<tr><td><b>" & x.name & "</b></td>") response.write("<td>" & x.value & "</td></tr>")
next
rs.MoveNext loop
AJAX – PHP - text
Bakker 2016
24
AJAX – PHP - text
<html>
<head>
<script>
function showHint(str) { if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
} };
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
} }
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
Bakker 2016
25
AJAX – PHP - text
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) { if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
} } } }
// Output "no suggestion" if no hint was found or output correct values echo $hint === "" ? "no suggestion" : $hint;
?>
Bakker 2016
26
AJAX – XML
AJAX – XML
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
} th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() { ..
..
</body>
</html>
Bakker 2016
28
AJAX – XML
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) { myFunction(xhttp);
} };
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) { var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) { table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td></tr>";
}
AJAX – XML
<?xml version="1.0" encoding="ISO-8859-1"?>
-<CATALOG>
-<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
-<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
-<CD>
</CATALOG>
Bakker 2016
30
XMLHttpRequest Level 2
W3C Working Group Note 18 November 2014
Abstract
The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.
Status of This Document
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at
http://www.w3.org/TR/.
Work on this document has been discontinued and it should not be referenced or used as a basis for implementation. However, the Web Applications Working Group continues to work on XMLHttpRequest Level 1 and the WHATWG continues to work on XMLHttprequest.
This is the 18 November 2014 Working Group Note of the XMLHttpRequest Level 2 document. This document is produced by the Web Applications (WebApps) Working Group. The WebApps Working Group is part of the Rich Web Clients Activity in the W3C Interaction Domain.
Please send comments to the WebApps Working Group's public mailing list public-webapps@w3.org with [XHRL2] at the start of the subject line. Archives of this list are available. See also W3C mailing list and archive usage guidelines.
Publication as a Working Group Note does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual