Documente Academic
Documente Profesional
Documente Cultură
What is AJAX?
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background
AJAX = Asynchronous JavaScript and XML.
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.
Example
varxhttp;
if(window.XMLHttpRequest) {
xhttp =newXMLHttpRequest();
}else{
// code for IE6, IE5
xhttp
=newActiveXObject("Microsoft.XMLHTTP"
);
}
<!DOCTYPE html>
<html>
<body>
<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.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
Description
open(method,
url, async)
send()
send(string)
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.php",t
rue);
xhttp.send();
<!DOCTYPE html>
<html>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "demo_get.php", true);
xhttp.send();
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "demo_get2.php?fname=Henry&lname=Ford", true);
xhttp.send();
}
</script>
</body>
</html>
POST Requests
Example
xhttp.open("POST","demo_post.php",true);
xhttp.send();
To POST data like an HTML form, add an HTTP header with
setRequestHeader(). Specify the data you want to send in
the send() method:
Example
xhttp.open("POST","ajax_test.php",true);
xhttp.setRequestHeader("Content-type","application/xwww-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
Method
Description
Async=true
When using async=true, specify a function to
execute when the response is ready in the
onreadystatechange event:
Example
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML =
xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
<!DOCTYPE html>
<html>
<body>
Async=false
To use async=false, change the third parameter in the open() method
to false:
xhttp.open("GET", "ajax_info.txt", false);
Using async=false is not recommended, but for a few small requests
this can be ok.
Remember that the JavaScript will NOT continue to execute, until the
server response is ready. If the server is busy or slow, the application
will hang or stop.
Note: When you use async=false, do NOT write an
onreadystatechange function - just put the code after the send()
statement:
Example
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
<!DOCTYPE html>
<html>
<body>
Description
responseText
responseXML
<!DOCTYPE html>
<html>
<body>
<!DOCTYPE html>
<html>
<body>
<h2>My CD Collection:</h2>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp, xmlDoc, txt, x, i;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
xmlDoc = xhttp.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>
Property
Description
readyState
status
<!DOCTYPE html>
<html>
<body>
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 on your website, you
should create ONE standard function for creating the
XMLHttpRequest object, and call this for each AJAX task.
The function call should contain the URL and what to do on
onreadystatechange (which is probably different for each
call):
Example
function loadDoc(cFunc) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cFunc(xhttp);
}
<!DOCTYPE html>
<html>
<body>
<!DOCTYPE html>
<html>
<body>
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 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))) {//The stristr() function searches for the first occurrence of a string inside another string.
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
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.php?q="+str, true);
xhttp.send();
}
Hometow
Job
n
Peter
Griffin
41
Quahog
Brewery
Lois
Griffin
40
Newport
Piano
Teacher
Joseph
Swanson
39
Quahog
Police
Officer
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.
<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.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<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>
Code explanation:
First, check if no person is selected
(str == ""). If no person is selected,
clear the content of the txtHint
placeholder 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
<!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"); // ...some PHP code for database "my_db Change database to "test"
$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>
AJAX 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
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
txtCDInfo placeholder with the HTML table
filled with XML data:
LoadXMLDoc()
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>";
}
document.getElementById("demo").innerHTML = table;
}
<!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() {
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>";
}
document.getElementById("demo").innerHTML = table;}
</script>
</body>
</html>
Applet
An applet is a little application. Prior to the
World Wide Web, the built-in writing and
drawing programs that came with Windows
were sometimes called "applets." On the Web,
using Java, the object-oriented programming
language, an applet is a small program that
can be sent along with a Web page to a user.
Java applets can perform interactive
animations, immediate calculations, or other
simple tasks without having to send a user
request back to the server.
Servlet
A servlet is a small program that runs
on a server. The term was coined in
the context of the Java applet, a
small program that is sent as a
separate file along with a Web (HTML
) page. Java applets, usually intended
for running on a client, can result in
such services as performing a
calculation for a user or positioning
an image based on user interaction.
PHP
PHP is an alternative to Microsoft's
Active Server Page (ASP) technology.
As with ASP, the PHP script is
embedded within a Web page along
with its HTML. Before the page is
sent to a user that has requested it,
the Web server calls PHP to interpret
and perform the operations called for
in the PHP script.
XML
XML stands for EXtensible Markup
Language
XML is a markup language much like
HTML
XML was designed to store and
transport data
XML was designed to be selfdescriptive
XML is a W3C Recommendation