Using Ajax
Ajax stands for Asynchronous JavaScript and XML,which, in simple terms, means using a set of methods built in to JavaScript to transfer data between the browser and a server in the background.
An excellent example of this technology is Google Maps in which new sections
of a map are downloaded from the server when needed, without requiring a page refresh.
Using Ajax not only substantially reduces the amount of data that must be sent back
and forth, but also makes web pages seamlessly dynamic—allowing them to behave
more like self-contained applications. The results are a much improved user interface
and better responsiveness.
Implementing Ajax using Javascript
Using XMLHttpRequest
There are three ways of creating an XMLHttpRequest object:
• IE 5: request = new ActiveXObject("Microsoft.XMLHTTP")
• IE 6+: request = new ActiveXObject("Msxml2.XMLHTTP")
• All others: request = new XMLHttpRequest()
This is the case because Microsoft chose to implement a change with the release of
Internet Explorer 6, while all other browsers use a slightly different method.Therefore, the code below will work for all major browsers released over the last few years.
A cross-browser Ajax function
<script>
function ajaxRequest()
{
try // Non IE Browser?
{ // Yes
var request = new XMLHttpRequest()
}
catch(e1)
{
try // IE 6+?
{ // Yes
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try // IE 5?
{ // Yes
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3) // There is no AJAX Support
{
request = false
}
}
}
return request
}
</script>
Explanation of the code:
Here we are using try...catch construct.The try keyword executes the non internet Explorer Ajax command,and upon success, jumps on to the final return statement, where the new object is returned.
Otherwise, a catch traps the error, and the subsequent command is executed. Again,
upon success, the new object is returned; otherwise, the final of the three commands is tried.. If that attempt fails, then the browser doesn’t support Ajax and the request
object is set to false; otherwise, the object is returned. So there you have it: a crossbrowser Ajax request function that you may wish to add to your library of useful JavaScript functions.
XMLHttpRequest object’s properties
onreadystatechange : Specifies an event-handling function to be called whenever the readyState property of an object changes.
readyState : An integer property that reports on the status of a request. It can have any of these values: 0 =Uninitialized, 1 = Loading, 2 = Loaded, 3 = Interactive, and 4 = Completed.
responseText: The data returned by the server in text format.
responseXML: The data returned by the server in XML format.
status: The HTTP status code returned by the server.
statusText : The HTTP status text returned by the server.
An XMLHttpRequest object’s methods
abort() : Aborts the current request.
getAllResponseHeaders() : Returns all headers as a string.
getResponseHeader(param) : Returns the value of param as a string.
open('method', 'url', 'asynch'): Specifies the HTTP method to use (Get or Post), the target URL, and whether the request should be handled asynchronously (true or false).
send(data) :Sends data to the target server using the specified HTTP method.
setRequestHeader('param', 'value') : Sets a header with a parameter/value pair.
The need for properties and methods:
These properties and methods give you control over what data you send to the server
and receive back, as well as a choice of send and receive methods. For example, you
can choose whether to request data in plain text (which could include HTML and
other tags) or in XML format. You can also decide whether you wish to use the Post
or Get method to send to the server.
Let’s look at the Post method first by creating a very simple pair of documents: a com‐
bination of HTML and JavaScript, and a PHP program to interact via Ajax with the
first.
Your First Ajax Program
Type or copy the code and save it as given:
urlpost.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
</head>
<body style='text-align:center'>
<h1>Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
params = "url=amazon.com/gp/aw"
request = new ajaxRequest()
request.open("POST", "urlpost.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
</script>
</body>
</html>
Note:Do not run it until you add its second part
urlpost.php
<?php // urlpost.php
if (isset($_POST['url']))
{
echo file_get_contents('http://' . SanitizeString($_POST['url']));
}
function SanitizeString($var)
{
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
Explanation of the code:
SanitizeString function helps in securing all posted data against hackers.
This program uses the file_get_contents PHP function to load in the web page at
the URL supplied to it in the Post variable $_POST['url']. The file_get_contents
function is versatile in that it loads in the entire contents of a file or web page from
either a local or a remote server; it even takes into account moved pages and other
redirects.
Using Get Instead of Post
As with submitting any form data,you can submit your data with Get though it is insecure.
Using Frameworks for Ajax
Now that you know how to code your own Ajax routines, you might like to investi‐
gate some of the free frameworks that are available to make it even easier, and which
offer many more advanced features,example :jQuery.
.Now we have reached a point where we will implement everything we have learnt by developing a social networking website make sure to check the next publish.
0 Comments