Ajax Technology
Ajax Technology
<div style="background-color:orange;text-align:center">
<p>Navigation section</p>
</div>
<div style="border:1px solid black;text-align:right ">
<p>Content section</p>
</div>
Attributes:
Attribute Description
Class Document wide identifier
Dir Specifies the direction of the text
Id Document wide identifier
title Specifies a title to associate with the element.
style Helps to include inline style sheet.
lang Sets the language code.
<!DOCTYPE html>
<html>
<body>
<div id="container" style="width:800px">
<div id="header" style="background-color:#FFA500;
title="hi"">
<h1 style="margin-bottom:0;">Main Title of Web
Page</h1></div>
<div id="menu" style="background-
color:#FFD700;height:200px;width:200px;float:left;">
<b>Menu</b><br>
HTML<br>
CSS<br>
JavaScript</div>
<div id="content" style="background-
color:#EEEEEE;height:200px;width:600px;float:left;">
Content goes here</div>
<div id="footer" style="background-
color:#FFA500;clear:both;text-align:center;">
Copyright © W3Schools.com</div>
</div>
</body>
innerHTML Example
The innerHTML property sets or returns the inner HTML of an
element.
Syntax
HTMLElementObject.innerHTML=text
<html>
<head>
<script>
function changeLink()
{
document.getElementById('myAnchor').innerHTML="W3Scho
ols";
document.getElementById('myAnchor').href="http://www.w3sc
hools.com";
document.getElementById('myAnchor').target="_blank";
}
</script>
</head>
<body>
<a id="myAnchor"
href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()" value="Change
link">
</body>
</html>
Formatting with getElementById
In this example, we use the getElementById property to detect
the color that the user has selected. We can then use
style.background to apply the new color. In both cases, we refer
to the HTML elements by their ID (using getElementById.)
<script type="text/javascript">
function changeColor(){
var newColor =
document.getElementById('colorPicker').value;
document.getElementById('colorMsg').style.background =
newColor;
}
</script>
<div id="colorMsg" style="font-
size:18px;width:150px;height:100px;padding:5px;">Choose
a background color...</div>
<select id="colorPicker"
onchange="JavaScript:changeColor()">
<option value="transparent">None</option>
<option value="yellow">Yellow</option>
<option value="salmon">Salmon</option>
<option value="lightblue">Light Blue</option>
<option value="limegreen">Lime Green</option>
</select>
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.
Ajax uses XHTML for content and CSS for presentation, as
well as the Document Object Model and JavaScript for
dynamic content display.
Conventional web application trasmit 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.
XML is commonly used as the format for receiving server
data, although any format, including plain text, can be used.
AJAX is a web browser technology independent of web
server software.
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.
JavaScript
Loosely typed scripting language
JavaScript function is called when an event in a page
occurs
Glue for the whole AJAX operation
DOM
API for accessing and manipulating structured documents
Represents the structure of XML and HTML documents
CSS
Allows for a clear separation of the presentation style from
the content and may be changed programmatically by
JavaScript
XMLHttpRequest
JavaScript object that performs asynchrous interaction with
the server
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)
Steps of AJAX Operation
1. A client event occurs
2. An XMLHttpRequest object is created
3. The XMLHttpRequest object is configured
4. The XMLHttpRequest object makes an asynchronous
request to the Webserver.
5. Webserver returns the result containing XML document.
6. The XMLHttpRequest object calls the callback() function
and processes the result.
7. The HTML DOM is updated
AJAX Example:
The AJAX application contains one div section and one button.
The div section will be used to display information returned
from a server.
The button calls a function named loadDoc(), if it is clicked:
<!DOCTYPE html>
<html>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change
Content</button>
</body>
</html>
Next, add a <script> tag to the page's head section. The script
section contains the loadLDoc() function:
<head>
<script>
function loadDoc()
{
.... AJAX script goes here ...
}
</script>
</head>
AJAX Script
<!DOCTYPE html>
<html>
<head>
<script>
function loadDoc()
{
Var xmlhttp;
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("myDiv").innerHTML=xmlhttp.resp
onseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change
Content</button>
</body>
</html>
Method Description
Specifies the type of request, the URL,
and if the request should be handled
asynchronously or not.
GET Requests
Example
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
If you want to send information with the GET method, add the
information to the URL:
Example
xmlhttp.open("GET","demo_get2.asp?
fname=Henry&lname=Ford",true);
xmlhttp.send();
POST Requests
A simple POST request:
Example
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
Method Description
Adds HTTP headers to the
request.
document.getElementById("myDiv").innerHTML=xmlhttp.resp
onseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
Async=false
To use async=false, change the third parameter in the open()
method to false:
xmlhttp.open("GET","ajax_info.txt",false);
Using async=false is not recommended, but for a few small
requests this can be ok.
Example
xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.resp
onseText;
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
Abort()
Property Description
Stores a function (or the name of a function)
onreadystatechange to be called automatically each time the
readyState property changes
Holds the status of the XMLHttpRequest.
Changes from 0 to 4:
0: request not initialized
readyState 1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found
In the onreadystatechange event, we specify what will happen
when the server response is ready to be processed.
When readyState is 4 and status is 200, the response is ready:
Example
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.resp
onseText;
}
}
Now dump the following data into this table using the following
SQL statements
<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
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($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 = mysql_query($query) or die(mysql_error());
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>