0% found this document useful (0 votes)
31 views27 pages

Ajax Technology

The document discusses the HTML <div> tag and its uses and attributes. The <div> tag is used to group large sections of HTML elements together and format them with CSS. It can define sections on a page and is a block-level element, unlike the span tag which is inline. Examples of using the <div> tag are also provided.

Uploaded by

sakshisunilaru08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views27 pages

Ajax Technology

The document discusses the HTML <div> tag and its uses and attributes. The <div> tag is used to group large sections of HTML elements together and format them with CSS. It can define sections on a page and is a block-level element, unlike the span tag which is inline. Examples of using the <div> tag are also provided.

Uploaded by

sakshisunilaru08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

AJAX

HTML <div> tag


Function:
The HTML <div> tag is used for defining a section of your
document. With the div tag, you can group large sections of
HTML elements together and format them with CSS.
The difference between the div tag and the span tag is that the
div tag is used with block-level elements whilst the span tag is
used with inline elements.
Example:

<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 Value Description


left
right Deprecated Defines alignment of the content
Align
center enclosed in div tag.
justify
Standard 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.

How AJAX Works

AJAX Browser Support


The list of major browsers which support AJAX.

 Mozilla Firefox 1.0 and above


 Netscape version 7.1 and above
 Apple Safari 1.2 and above.
 Microsoft Internet Exporer 5 and above
 Konqueror
 Opera 7.6 and above

Technologies Used in AJAX

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>

The XMLHttpRequest Object


All modern browsers support the XMLHttpRequest object (IE5
and IE6 use an ActiveXObject).
The XMLHttpRequest object is used to exchange data with a
server behind the scenes.
That it is possible to update parts of a web page, without
reloading the whole page.

Create an XMLHttpRequest Object


All modern browsers (IE7+, Firefox, Chrome, Safari, and
Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX
Object:
variable=new ActiveXObject("Microsoft.XMLHTTP");
To handle all modern browsers, including IE5 and IE6, check if
the browser supports the XMLHttpRequest object. If it does,
create an XMLHttpRequest object, if not, create an
ActiveXObject:
Example
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");
}

The 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:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

Method Description
Specifies the type of request, the URL,
and if the request should be handled
asynchronously or not.

open(method,url,async) method: the type of request: GET or


POST
url: the location of the file on the server
async: true (asynchronous) or false
(synchronous)
Sends the request off to the server.
send(string)
string: Only used for POST requests

GET or POST Method


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

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
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-
form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

Method Description
Adds HTTP headers to the
request.

setRequestHeader(header,value) header: specifies the header


name
value: specifies the header
value

The url - A File On a Server


The url parameter of the open() method, is an address to a file on
a server:
xmlhttp.open("GET","ajax_test.asp",true);
The file can be any kind of file, like .txt and .xml, or server
scripting files like .asp and .php

Asynchronous - True or False?


AJAX stands for Asynchronous JavaScript and XML, and for
the XMLHttpRequest object to behave as AJAX, the async
parameter of the open() method has to be set to true:
xmlhttp.open("GET","ajax_test.asp",true);
Sending asynchronous requests is a huge improvement for web
developers. Many of the tasks performed on the server are very
time consuming. Before AJAX, this operation could cause the
application to hang or stop.
With AJAX, the JavaScript does not have to wait for the server
response, but can instead:
 execute other scripts while waiting for server response
 deal with the response when the response ready
Async=true
When using async=true, specify a function to execute when the
response is ready in the onreadystatechange event:
Example
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();

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;

AJAX - Server Response

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

The responseText Property


If the response from the server is not XML, use the
responseText property.
The responseText property returns the response as a string
Example
document.getElementById("myDiv").innerHTML=xmlhttp.resp
onseText;

The responseXML Property


If the response from the server is XML, and you want to parse it
as an XML object, use the responseXML property:
Example
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;
AJAX - The onreadystatechange Event

Abort()

Cancels the current request.


getAllResponseHeaders()

Returns the complete set of HTTP headers as a string.

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:

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

mysql_real_escape_string() calls MySQL's library function


mysql_real_escape_string, which prepends backslashes to the
following characters: \x00, \n, \r, \, ', " and \x1a.

PHP and AJAX Example:

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

Now dump the following data into this table using the following
SQL statements

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);
Client Side HTML file
Now lets have our client side HTML file which is ajax.html and
it will have following code

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

Server Side PHP file

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

//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
while($row = mysql_fetch_array($qry_result)){
$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;
?>

You might also like