• No results found

PHP and AJAX

N/A
N/A
Protected

Academic year: 2021

Share "PHP and AJAX"

Copied!
31
0
0

Bezig met laden.... (Bekijk nu de volledige tekst)

Hele tekst

(1)

PHP and AJAX

Exchange data interface

(2)

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

(3)

AJAX

AJAX example

XMLHttpRequest

Send a Request To a Server

Server response

The onreadystatechange event

ASP example

PHP example

XML example

(4)

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

(5)

PHP and AJAX Example

(6)

PHP and AJAX Example

Bakker 2016

6

(7)

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;

(8)

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

(9)

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);

(10)

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

(11)

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>

(12)

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

(13)

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.

(14)

XMLHttpRequest

var xhttp;

if (window.XMLHttpRequest) {

xhttp = new XMLHttpRequest();

} else {

xhttp = new

ActiveXObject("Microsoft.XMLHTTP");

}

Bakker 2016

14

(15)

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();

(16)

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

(17)

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

(18)

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

(19)

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:

(20)

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

(21)

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;

}

};

(22)

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

(23)

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

(24)

AJAX – PHP - text

Bakker 2016

24

(25)

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

(26)

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

(27)

AJAX – XML

(28)

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

(29)

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>";

}

(30)

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

(31)

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

Referenties

GERELATEERDE DOCUMENTEN

Cases and controls were recruited from the southeast of Scotland, and ascertainment has been previously described as part of the International Schizophrenia Consortium studies.

The seminar creates an opportunity for younger scholars from Berlin to develop an appropriate style of research by presenting their own work and familiarizing

Concerning the influence of continuous improvement on the working environment, our findings revealed that the influence is highly dependent on the practiced leadership

env@#1@parse executes the body twice: the first time to save the body while ignoring the arguments; and the second time to process the environment defini- tion itself while ignoring

The output of your code is saved into the file provided as the second optional argument of \iexec (the default value is iexec.tmp ):. 6 Today is \iexec[date.txt]{date +\%e-\%b-\%Y |

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.. Ut purus elit, vestibulum ut, placerat ac, adipisc- ing

The glossaries-extra package temporarily modifies commands like \gls or \glsxtrshort that occur in fields, when any of those field is accessed through linking commands.. First use:

 Subject to the conditions and other restrictions set out in the terms and conditions of the Securities, the Issuer may adjust the terms and conditions of the Securities without