Nothing Special   »   [go: up one dir, main page]

AJAX Tutorial

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 61

AJAX Tutorial

AJAX is a developer's dream, because you can:

 Read data from a web server - after the page has loaded
 Update a web page without reloading the page
 Send data to a web server - in the background

AJAX Example Explained


HTML Page
<!DOCTYPE html>
<html>
<body>

<div id="demo">
  <h2>Let AJAX change this text</h2>
  <button type="button" Content</button>
</div>

</body>
</html>

The HTML page contains a <div> section and a <button>.

The <div> section is used to display information from a server.

The <button> calls a function (if it is clicked).

The function requests data from a web server and displays it:

Function loadDoc()
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp. {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

ajax_info.txt File (is on webserver in htdocs folder)


<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

When we run the html page in browser we get


And when we click the change content button we get

What is AJAX?

AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

 A browser built-in XMLHttpRequest object (to request data from a web server)
 JavaScript and HTML DOM (to display or use the data)

AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally
common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without reloading the
whole page.
How AJAX Works

 1. An event occurs in a web page (the page is loaded, a button is clicked)


 2. An XMLHttpRequest object is created by JavaScript
 3. The XMLHttpRequest object sends a request to a web server
 4. The server processes the request
 5. The server sends a response back to the web page
 6. The response is read by JavaScript
 7. Proper action (like page update) is performed by JavaScript
AJAX - The XMLHttpRequest Object
The keystone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a web server behind the scenes.
This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-in
XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Example
var xhttp = new XMLHttpRequest();

Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same
server.

The examples on W3Schools all open XML files located on the W3Schools domain.

If you want to use the example above on one of your own web pages, the XML files you load must
be located on your own server.

Older Browsers (IE5 and IE6)

Old versions of Internet Explorer (5/6) use an ActiveX object instead of the XMLHttpRequest
object:

variable = new ActiveXObject("Microsoft.XMLHTTP");

To handle IE5 and IE6, check if the browser supports the XMLHttpRequest object, or else create an
ActiveX object:
Example
if (window.XMLHttpRequest) {
   // code for modern browsers
   xmlhttp = new XMLHttpRequest();
 } else {
   // code for old IE browsers
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Complete code checking browser support for ajax (XMLHttpRequest)

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<p id="demo">Let AJAX change this text.</p>

<button type="button" Content</button>

<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>

</body>
</html>

Note : ajax_info.txt file same as above example

ajax_info.txt File (is on webserver in htdocs folder)


<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

When we run the html page in browser we get


And when we click the change content button we get

XMLHttpRequest Object Methods


Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

Specifies the request

method: the request type GET or POST


open(method, url, async, user, psw) url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password

Sends the request to the server


send()
Used for GET requests

Sends the request to the server.


send(string)
Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent


XMLHttpRequest Object Properties
Property Description

onreadystatechange Defines a function to be called when the readyState property changes

Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
readyState
2: request received
3: processing request
4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data

Returns the status-number of a request


200: "OK"
status 403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

AJAX - Send a Request To a Server


he XMLHttpRequest object is used to exchange data with a server.
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();

Method Description

Specifies the type of request

open(method, url,
method: the type of request: GET or POST
async)
url: the server (file) location
async: true (asynchronous) or false (synchronous)

send() Sends the request to the server (used for GET)

send(string) Sends the request to the server (used for POST)

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

 A cached file is not an option (update a file or database on the server).


 Sending a large amount of data to the server (POST has no size limitations).
 Sending user input (which can contain unknown characters), POST is more robust and secure than
GET.

GET Requests

A simple GET request:

Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();

Complete code

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>


<button type="button" data</button>

<p id="demo"></p>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
}
</script>

</body>
</html>

output

When we clock on Request data button we get

In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:

Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();

Complete code

<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>

<button type="button" data</button>

<p>Click the button several times to see if the time changes, or if the file is cached.</p>

<p id="demo"></p>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
}
</script>

</body>
</html>

Now if run the above html file we get

When we click on Request data button, we get following

If you want to send information with the GET method, add the information to the URL:

Example
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
AJAX - Server Response
The onreadystatechange Property

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a function to be executed when the readyState changes.

The status property and the statusText property holds the status of the XMLHttpRequest object.

Property Description

onreadystatechange Defines a function to be called when the readyState property changes

Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
readyState
2: request received
3: processing request
4: request finished and response is ready

200: "OK"
403: "Forbidden"
status
404: "Page not found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Example
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp. {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.

Complete code

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" Content</button>
</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>

</body>
</html>

When we run the above html file in browser we get

When we click on change Content button, we get

Using a Callback Function

A callback function is a function passed as a parameter to another function.

If you have more than one AJAX task in a website, you should create one function for executing the
XMLHttpRequest object, and one callback function for each AJAX task.
The function call should contain the URL and what function to call when the response is ready.

Example
loadDoc("url-1", myFunction1);

loadDoc("url-2", myFunction2);

function loadDoc(url, cFunction) {


  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp. {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

function myFunction1(xhttp) {
  // action goes here
}
function myFunction2(xhttp) {
  // action goes here
}

Complete html file code

<!DOCTYPE html>
<html>
<body>

<div id="demo">

<h2>The XMLHttpRequest Object</h2>

<button type="button" myFunction)">Change Content


</button>
</div>

<script>
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML =
xhttp.responseText;
}
</script>
</body>
</html>

When we run above html file in browser we get

And when we click on Change Content button we get

The responseText Property

The responseText property returns the server response as a JavaScript string, and you can use it
accordingly:

Example
document.getElementById("demo").innerHTML = xhttp.responseText;

Complete code

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" Content</button>
</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>

</body>
</html>

When we run above html file in browser we get

And when we click on Change Content button we get

The responseXML Property

The XMLHttpRequest object has an in-built XML parser.


The responseXML property returns the server response as an XML DOM object.

Using this property you can parse the response as an XML DOM object:

Example

Request the file cd_catalog.xml and parse the response:

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;
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();

Complete Code

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<p id="demo"></p>

<script>
var xhttp, xmlDoc, txt, x, i;
xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
xmlDoc = this.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt = txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
</script>

</body>
</html>

cd_catalog.xml File

<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>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
<CD>
<TITLE>Still got the blues</TITLE>
<ARTIST>Gary Moore</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Virgin records</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Eros</TITLE>
<ARTIST>Eros Ramazzotti</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>BMG</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
<CD>
<TITLE>One night only</TITLE>
<ARTIST>Bee Gees</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1998</YEAR>
</CD>
<CD>
<TITLE>Sylvias Mother</TITLE>
<ARTIST>Dr.Hook</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS</COMPANY>
<PRICE>8.10</PRICE>
<YEAR>1973</YEAR>
</CD>
</CATALOG>
Output

The XMLHttpRequest Object

Bob Dylan
Bonnie Tyler
Dolly Parton
Gary Moore
Eros Ramazzotti
Bee Gees
Dr.Hook

You will learn a lot more about XML DOM in the DOM chapters of this tutorial.

The getAllResponseHeaders() Method

The getAllResponseHeaders() method returns all header information from the server response.

Example
var xhttp = new XMLHttpRequest();
xhttp. {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
    this.getAllResponseHeaders();
 }
};

Complete code
<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<p>The getAllResponseHeaders() function returns all the header information of a resource, like length,
server-type, content-type, last-modified, etc:</p>

<p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
</script>
</body>
</html>

Output

The XMLHttpRequest Object

The getAllResponseHeaders() function returns all the header information of a resource, like length, server-
type, content-type, last-modified, etc:

accept-ranges: bytes age: 3453 cache-control: public,max-age=14400,public content-encoding: gzip content-


length: 245 content-type: text/plain date: Wed, 04 Mar 2020 04:58:54 GMT etag: "15bfdeee0ffd21:0" last-
modified: Tue, 18 Jul 2017 16:14:29 GMT server: ECS (ndl/D35C) vary: Accept-Encoding x-cache: HIT x-
firefox-spdy: h2 x-frame-options: SAMEORIGIN x-powered-by: ASP.NET

The getResponseHeader() Method

The getResponseHeader() method returns specific header information from the server response.

Example
var xhttp = new XMLHttpRequest();
xhttp. {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
    this.getResponseHeader("Last-Modified");
 }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

Complete Code
<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<p>The getResponseHeader() function is used to return specific header information from a resource, like
length, server-type, content-type, last-modified, etc:</p>

<p>Last modified: <span id="demo"></span></p>

<script>
var xhttp=new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
</script>

</body>
</html>

Output

The XMLHttpRequest Object

The getResponseHeader() function is used to return specific header information from a resource,
like length, server-type, content-type, last-modified, etc:

Last modified: Tue, 18 Jul 2017 16:14:29 GMT

AJAX XML Example


AJAX can be used for interactive communication with an XML file.

AJAX XML Example

The following example will demonstrate how a web page can fetch information from an XML file
with AJAX:

Example

When we click on Get CD Info button, we get following


Title Artist
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyler
Greatest Hits Dolly Parton
Still got the blues Gary Moore
Eros Eros Ramazzotti
One night only Bee Gees
Sylvias Mother Dr.Hook
Maggie May Rod Stewart
Romanza Andrea Bocelli
When a man loves a woman Percy Sledge
Black angel Savage Rose
1999 Grammy Nominees Many
For the good times Kenny Rogers
Big Willie style Will Smith
Tupelo Honey Van Morrison
Soulsville Jorn Hoel
The very best of Cat Stevens
Stop Sam Brown
Bridge of Spies T'Pau
Private Dancer Tina Turner
Midt om natten Kim Larsen
Pavarotti Gala Concert Luciano Pavarotti
The dock of the bay Otis Redding
Picture book Simply Red
Red The Communards
Unchain my heart Joe Cocker

Example Explained

When a user clicks on the "Get CD info" button above, the loadDoc() function is executed.

The loadDoc() function creates an XMLHttpRequest object, adds the function to be executed when
the server response is ready, and sends the request off to the server.

When the server response is ready, an HTML table is built, nodes (elements) are extracted from the
XML file, and it finally updates the element "demo" with the HTML table filled with XML data:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp. {
    if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
    }
  };
  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>";
 }
  document.getElementById("demo").innerHTML = table;
}
The XML File

The XML file used in the example above looks like this: "cd_catalog.xml".

<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>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
<CD>
<TITLE>Still got the blues</TITLE>
<ARTIST>Gary Moore</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Virgin records</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Eros</TITLE>
<ARTIST>Eros Ramazzotti</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>BMG</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
<CD>
<TITLE>One night only</TITLE>
<ARTIST>Bee Gees</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1998</YEAR>
</CD>
<CD>
<TITLE>Sylvias Mother</TITLE>
<ARTIST>Dr.Hook</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS</COMPANY>
<PRICE>8.10</PRICE>
<YEAR>1973</YEAR>
</CD>
<CD>
<TITLE>Maggie May</TITLE>
<ARTIST>Rod Stewart</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Pickwick</COMPANY>
<PRICE>8.50</PRICE>
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Romanza</TITLE>
<ARTIST>Andrea Bocelli</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.80</PRICE>
<YEAR>1996</YEAR>
</CD>
<CD>
<TITLE>When a man loves a woman</TITLE>
<ARTIST>Percy Sledge</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Atlantic</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Black angel</TITLE>
<ARTIST>Savage Rose</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Mega</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1995</YEAR>
</CD>
<CD>
<TITLE>1999 Grammy Nominees</TITLE>
<ARTIST>Many</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Grammy</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1999</YEAR>
</CD>
<CD>
<TITLE>For the good times</TITLE>
<ARTIST>Kenny Rogers</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Mucik Master</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1995</YEAR>
</CD>
<CD>
<TITLE>Big Willie style</TITLE>
<ARTIST>Will Smith</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
<CD>
<TITLE>Tupelo Honey</TITLE>
<ARTIST>Van Morrison</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1971</YEAR>
</CD>
<CD>
<TITLE>Soulsville</TITLE>
<ARTIST>Jorn Hoel</ARTIST>
<COUNTRY>Norway</COUNTRY>
<COMPANY>WEA</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1996</YEAR>
</CD>
<CD>
<TITLE>The very best of</TITLE>
<ARTIST>Cat Stevens</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Island</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Stop</TITLE>
<ARTIST>Sam Brown</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>A and M</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Bridge of Spies</TITLE>
<ARTIST>T'Pau</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Siren</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Private Dancer</TITLE>
<ARTIST>Tina Turner</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Capitol</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1983</YEAR>
</CD>
<CD>
<TITLE>Midt om natten</TITLE>
<ARTIST>Kim Larsen</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Medley</COMPANY>
<PRICE>7.80</PRICE>
<YEAR>1983</YEAR>
</CD>
<CD>
<TITLE>Pavarotti Gala Concert</TITLE>
<ARTIST>Luciano Pavarotti</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>DECCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1991</YEAR>
</CD>
<CD>
<TITLE>The dock of the bay</TITLE>
<ARTIST>Otis Redding</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Stax Records</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1968</YEAR>
</CD>
<CD>
<TITLE>Picture book</TITLE>
<ARTIST>Simply Red</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Elektra</COMPANY>
<PRICE>7.20</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Red</TITLE>
<ARTIST>The Communards</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>London</COMPANY>
<PRICE>7.80</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Unchain my heart</TITLE>
<ARTIST>Joe Cocker</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>EMI</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1987</YEAR>
</CD>
</CATALOG>

AJAX PHP Example


AJAX is used to create more interactive applications.
AJAX PHP Example
The following example demonstrates how a web page can communicate with a web server while a
user types characters in an input field:
Example

When we start typing in above test box, suggestions are provided above

Example Explained
In the example above, when a user types a character in the input field, a function called showHint()
is executed.
The function is triggered by the onkeyup event.
Here is the HTML code:
Example
<html>
<head>
<script>
function showHint(str) {
  if (str.length == 0) {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp. {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("txtHint").innerHTML = this.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" > </form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

When we run the above html file in browser, we get

When we type in the above text box, it provides you the hints or suggestions

Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint
placeholder and exit the function.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a PHP file (gethint.php) on the server
 Notice that q parameter is added gethint.php?q="+str
 The str variable holds the content of the input field

The PHP File - "gethint.php"


The PHP file checks an array of names, and returns the corresponding name(s) to the browser:
<?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;
?>
AJAX Database Example
AJAX can be used for interactive communication with a database.
AJAX Database Example
The following example will demonstrate how a web page can fetch information from a database
with AJAX:
Example

When we click on the combo box we get

Example Explained - The showCustomer() Function


When a user selects a customer in the dropdown list above, a function called showCustomer() is
executed. The function is triggered by the onchange event:

showCustomer
function showCustomer(str) {
  var xhttp;
  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
 }
  xhttp = new XMLHttpRequest();
  xhttp. {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById("txtHint").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "getcustomer.php?q="+str, true);
  xhttp.send();
}

The showCustomer() function does the following:

 Check if a customer is selected


 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

Complete Code of above html file


<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>

<h2>The XMLHttpRequest Object</h2>

<form action="">
<select name="customers" > <option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>

<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
</script>
</body>
</html>

The AJAX Server Page


The page on the server called by the JavaScript above is a PHP file called "getcustomer.php".
The source code in "getcustomer.php" runs a query against a database, and returns the result in an
HTML table:
<?php
$mysqli = new mysqli("servername", "username", "password", "dbname");
if($mysqli->connect_error) {
  exit('Could not connect');
}

$sql = "SELECT customerid, companyname, contactname, address, city, postalcode, country


FROM customers WHERE customerid = ?";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();

echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>

Output

XML Applications
This chapter demonstrates some HTML applications using XML, HTTP, DOM, and JavaScript.

The XML Document Used

In this chapter we will use the XML file called "cd_catalog.xml".

Display XML Data in an HTML Table

This example loops through each <CD> element, and displays the values of the <ARTIST> and the
<TITLE> elements in an HTML table:

Example
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

th, td {
  padding: 5px;
}
</style>
</head>
<body>

<table id="demo"></table>

<script>
function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp. {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xmlhttp.open("GET", "cd_catalog.xml", true);
  xmlhttp.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>";
 }
  document.getElementById("demo").innerHTML = table;
}
</script>

</body>
</html>

Output

When we clock on Het my CD collection, we get

Artist Title
Bob Dylan Empire Burlesque
Bonnie Tyler Hide your heart
Dolly Parton Greatest Hits
Gary Moore Still got the blues
Eros Ramazzotti Eros
Bee Gees One night only
Dr.Hook Sylvias Mother
Rod Stewart Maggie May
Andrea Bocelli Romanza
Percy Sledge When a man loves a woman
Savage Rose Black angel
Many 1999 Grammy Nominees
Kenny Rogers For the good times
Will Smith Big Willie style
Van Morrison Tupelo Honey
Jorn Hoel Soulsville
Cat Stevens The very best of
Sam Brown Stop
T'Pau Bridge of Spies
Tina Turner Private Dancer
Kim Larsen Midt om natten
Luciano Pavarotti Pavarotti Gala Concert
Otis Redding The dock of the bay
Simply Red Picture book
The Communards Red
Joe Cocker Unchain my heart

Cd_catalog.xml File
<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>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
<CD>
<TITLE>Still got the blues</TITLE>
<ARTIST>Gary Moore</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Virgin records</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Eros</TITLE>
<ARTIST>Eros Ramazzotti</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>BMG</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
<CD>
<TITLE>One night only</TITLE>
<ARTIST>Bee Gees</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1998</YEAR>
</CD>
<CD>
<TITLE>Sylvias Mother</TITLE>
<ARTIST>Dr.Hook</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS</COMPANY>
<PRICE>8.10</PRICE>
<YEAR>1973</YEAR>
</CD>
<CD>
<TITLE>Maggie May</TITLE>
<ARTIST>Rod Stewart</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Pickwick</COMPANY>
<PRICE>8.50</PRICE>
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Romanza</TITLE>
<ARTIST>Andrea Bocelli</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.80</PRICE>
<YEAR>1996</YEAR>
</CD>
<CD>
<TITLE>When a man loves a woman</TITLE>
<ARTIST>Percy Sledge</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Atlantic</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Black angel</TITLE>
<ARTIST>Savage Rose</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Mega</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1995</YEAR>
</CD>
<CD>
<TITLE>1999 Grammy Nominees</TITLE>
<ARTIST>Many</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Grammy</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1999</YEAR>
</CD>
<CD>
<TITLE>For the good times</TITLE>
<ARTIST>Kenny Rogers</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Mucik Master</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1995</YEAR>
</CD>
</CATALOG>

Display the First CD in an HTML div Element

This example uses a function to display the first CD element in an HTML element with
id="showCD":
Example
<!DOCTYPE html>
<html>
<body>

<div id='showCD'></div>

<script>
displayCD(0);

function displayCD(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}

function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("CD");
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>

</body>
</html>

Output
Artist: Bob Dylan
Title: Empire Burlesque
Year: 1985

Navigate Between the CDs

To navigate between the CDs in the example above, create a next() and previous() function:
Example
function next() {
  // display the next CD, unless you are on the last CD
  if (i < len-1) {
    i++;
    displayCD(i);
 }
}

function previous() {
  // display the previous CD, unless you are on the first CD
  if (i > 0) {
    i--;
    displayCD(i);
  }
}</html>

Compete Code
<!DOCTYPE html>
<html>
<body>

<div id='showCD'></div><br>
<input type="button" value="<<">
<input type="button" value=">>">

<script>
var i = 0, len;
displayCD(i);

function displayCD(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}

function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("CD");
len = x.length;
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}

function next() {
if (i < len-1) {
i++;
displayCD(i);
}
}

function previous() {
if (i > 0) {
i--;
displayCD(i);
}
}
</script>

</body>
</html>

Output

We can click forward and backward arrow buttons to move to next or previous record in database.

Show Album Information When Clicking On a CD

The last example shows how you can show album information when the user clicks on a CD:

Example
function displayCD(i) {
  document.getElementById("showCD").innerHTML =
  "Artist: " +
  x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
  "<br>Title: " +
  x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
  "<br>Year: " +
  x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}

Complete Code
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>

<p>Click on a CD to display album information.</p>


<p id='showCD'></p>
<table id="demo"></table>

<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("CD");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++) {
table += "<tr + i + ")'><td>";
table += x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
table += "</td><td>";
table += x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;

function displayCD(i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>

</body>
</html>

Output
If we click on Gary Moore in the table displayed it shows as follows
PHP - AJAX

PHP - AJAX Introduction

AJAX is about updating parts of a web page, without reloading the whole page.

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with
the server behind the scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should
change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works


AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:

 XMLHttpRequest object (to exchange data asynchronously with a server)


 JavaScript/DOM (to display/interact with the information)
 CSS (to style the data)
 XML (often used as the format for transferring data)

AJAX applications are browser- and platform-independent!

Google Suggest

AJAX was made popular in 2005 by Google, with Google Suggest.

Google Suggest is using AJAX to create a very dynamic web interface: When you start typing in
Google's search box, a JavaScript sends the letters off to a server and the server returns a list of
suggestions.

Start Using AJAX Today

In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without
reloading the whole page. The server script will be written in PHP.

If you want to learn more about AJAX, visit our AJAX tutorial.

PHP - AJAX and PHP

AJAX is used to create more interactive applications.

AJAX PHP Example


The following example will demonstrate how a web page can communicate with a web server while
a user type characters in an input field:
Example Explained
In the example above, when a user types a character in the input field, a function called
"showHint()" is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:

Example

<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp. {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.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" > </form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
Output
Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint
placeholder and exit the function.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a PHP file (gethint.php) on the server
 Notice that q parameter is added to the url (gethint.php?q="+str)
 And the str variable holds the content of the input field

The PHP File - "gethint.php"


The PHP file checks an array of names, and returns the corresponding name(s) to the browser:

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

PHP - AJAX and MySQL


AJAX can be used for interactive communication with a database.

AJAX Database Example


The following example will demonstrate how a web page can fetch information from a database
with AJAX:

Example Explained - The MySQL Database


The database table we use in the example above looks like this:

id FirstName LastName Age Hometown Job


1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

Example Explained
In the example above, when a user selects a person in the dropdown list above, a function called
"showUser()" is executed.

The function is triggered by the onchange event.

Here is the HTML code:

Example

<html>
<head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp. {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","getuser.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<form>
<select name="users" >   <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

Output

Code explanation:

First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and
exit the function. If a person is selected, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a query against a MySQL database, and returns the result in
an HTML table:

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['FirstName'] . "</td>";
    echo "<td>" . $row['LastName'] . "</td>";
    echo "<td>" . $row['Age'] . "</td>";
    echo "<td>" . $row['Hometown'] . "</td>";
    echo "<td>" . $row['Job'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

1. PHP opens a connection to a MySQL server


2. The correct person is found
3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder

PHP Example - AJAX and XML


AJAX can be used for interactive communication with an XML file.
AJAX XML Example
The following example will demonstrate how a web page can fetch information from an XML file
with AJAX:

Example Explained - The HTML Page


When a user selects a CD in the dropdown list above, a function called "showCD()" is executed.
The function is triggered by the "onchange" event:
<html>
<head>
<script>
function showCD(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
 }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
  xmlhttp. {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("txtHint").innerHTML=this.responseText;
    }
 }
  xmlhttp.open("GET","getcd.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
Select a CD:
<select name="cds" > <option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>

</body>
</html>

The showCD() function does the following:

 Check if a CD is selected
 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getcd.php".

The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and
returns the result as HTML:

<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();


$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++) {


  //Process only element nodes
  if ($x->item($i)->nodeType==1) {
    if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
      $y=($x->item($i)->parentNode);
    }
  }
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++) {
  //Process only element nodes
  if ($cd->item($i)->nodeType==1) {
    echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
    echo($cd->item($i)->childNodes->item(0)->nodeValue);
    echo("<br>");
  }
}
?>
When the CD query is sent from the JavaScript to the PHP page, the following happens:

1. PHP creates an XML DOM object


2. Find all <artist> elements that matches the name sent from the JavaScript
3. Output the album information (send to the "txtHint" placeholder)

PHP Example - AJAX Live Search

AJAX can be used to create more user-friendly and interactive searches.


AJAX Live Search

The following example will demonstrate a live search, where you get search results while you type.

Live search has many benefits compared to traditional searching:

 Results are shown as you type


 Results narrow as you continue typing
 If results become too narrow, remove characters to see a broader result

Search for a W3Schools page in the input field below:

The results in the example above are found in an XML file (links.xml). To make this example small
and simple, only six results are available.

Example Explained - The HTML Page

When a user types a character in the input field above, the function "showResult()" is executed. The
function is triggered by the "onkeyup" event:

<html>
<head>
<script>
function showResult(str) {
  if (str.length==0) {
    document.getElementById("livesearch").innerHTML="";
    document.getElementById("livesearch").style.border="0px";
    return;
 }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
  xmlhttp. {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("livesearch").innerHTML=this.responseText;
      document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
 }
  xmlhttp.open("GET","livesearch.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" > <div id="livesearch"></div>
</form>

</body>
</html>

Source code explanation:

If the input field is empty (str.length==0), the function clears the content of the livesearch
placeholder and exits the function.

If the input field is not empty, the showResult() function executes the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the input field)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "livesearch.php".

The source code in "livesearch.php" searches an XML file for titles matching the search string and
returns the result:

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL


$q=$_GET["q"];

//lookup all links from the xml file if length of q>0


if (strlen($q)>0) {
  $hint="";
  for($i=0; $i<($x->length); $i++) {
    $y=$x->item($i)->getElementsByTagName('title');
    $z=$x->item($i)->getElementsByTagName('url');
    if ($y->item(0)->nodeType==1) {
      //find a link matching the search text
      if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
        if ($hint=="") {
          $hint="<a href='" .
          $z->item(0)->childNodes->item(0)->nodeValue .
          "' target='_blank'>" .
          $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        } else {
          $hint=$hint . "<br /><a href='" .
          $z->item(0)->childNodes->item(0)->nodeValue .
          "' target='_blank'>" .
          $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      }
    }
  }
}

// Set output to "no suggestion" if no hint was found


// or to the correct values
if ($hint=="") {
  $response="no suggestion";
} else {
  $response=$hint;
}

//output the response


echo $response;
?>

Ouput

If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:

 Load an XML file into a new XML DOM object


 Loop through all <title> elements to find matches from the text sent from the JavaScript
 Sets the correct url and title in the "$response" variable. If more than one match is found, all
matches are added to the variable
 If no matches are found, the $response variable is set to "no suggestion"

PHP Example - AJAX Poll

AJAX Poll
The following example will demonstrate a poll where the result is shown without reloading.

Do you like PHP and AJAX so far?

Yes:
No:

Example Explained - The HTML Page


When a user chooses an option above, a function called "getVote()" is executed. The function is
triggered by the "onclick" event:

<html>
<head>
<script>
function getVote(int) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
  xmlhttp. {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("poll").innerHTML=this.responseText;
    }
 }
  xmlhttp.open("GET","poll_vote.php?vote="+int,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" > <br>No:
<input type="radio" name="vote" value="1" > </form>
</div>

</body>
</html>

The getVote() function does the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "poll_vote.php":

<?php
$vote = $_REQUEST['vote'];

//get content of textfile


$filename = "poll_result.txt";
$content = file($filename);

//put content in array


$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
  $yes = $yes + 1;
}
if ($vote == 1) {
  $no = $no + 1;
}

//insert votes to txt file


$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

The value is sent from the JavaScript, and the following happens:

1. Get the content of the "poll_result.txt" file


2. Put the content of the file in variables and add one to the selected variable
3. Write the result to the "poll_result.txt" file
4. Output a graphical representation of the poll result

The Text File


The text file (poll_result.txt) is where we store the data from the poll.

It is stored like this:

0||0

The first number represents the "Yes" votes, the second number represents the "No" votes.

Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just
the web server (PHP).

You might also like