Unit - 5 Ajax
Unit - 5 Ajax
JavaScript And XML
UNIT - 5
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");
}
XMLHttpRequest.response
• The XMLHttpRequest response property returns
the response's body content as an ArrayBuffer,
Blob, Document, JavaScript Object, or DOMString,
depending on the value of the request's
responseType property.
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.response);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
Method Description
open(method,url,async) Specifies the type of request, the URL, and if the
request should be handled asynchronously or not.
</form>
<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>
</html>
<?php // Set output to "no suggestion" if no hint
// Fill up array with names were //found or to the correct values
$a[]="Wenche"; if ($hint == "")
{
$a[]="Vicky";
$response="no suggestion";
$a[]="Mahesh"; }
//get the q parameter from URL else
$q=$_GET["q"]; {
//lookup all hints from array if length of q>0 $response=$hint;
if (strlen($q) > 0) }
{ //output the response
echo $response;
$hint="";
?>
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
XML Http Request Object
• XMLHttpRequest Methods
abort()
• Cancels the current request.
getAllResponseHeaders()
• Returns the complete set of HTTP headers as a string.
getResponseHeader( headerName )
• Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
• Specifies the method, URL, and other optional attributes of a request.
send( content )
• Sends the request.
setRequestHeader( label, value )
• Adds a label/value pair to the HTTP header to be sent. XMLHttpRequest Properties
onreadystatechange
• An event handler for an event that fires at every state change.
readyState
• The readyState property defines the current state of the XMLHttpRequest object.
XML Http Request Object
• received from the server.
responseText
• Returns the response as a string.
responseXML
• Returns the response as XML. This property returns an XML
document object, which can be examined and parsed using
the W3C DOM node tree methods and properties.
status
• Returns the status as a number (e.g., 404 for "Not Found"
and 200 for "OK").
statusText
• Returns the status as a string (e.g., "Not Found" or "OK").
onreadystatechange Property
Property Description
onreadystatechange Defines a function to be called when the readyState property
changes
function myCallBack() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log(xmlhttp.responseText);
}
}
Callback function as an named function
3. Set the value of the onreadystatechange property to the name of
the function.
function start() {
var xmlhttp = new XMLHttpRequest();
var contentDiv = document.getElementById("Content");
xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=myCallBack;
xmlhttp.setRequestHeader("Content-Type","application/x-www-
form-urlencoded;charset=UTF-8");
xmlhttp.send("FirstName=Nat&LastName=Dunn");
}
AJAX XML Example
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", “CDCatalog.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>
What is synchronous request in AJAX
• AJAX can access the server both synchronously
and asynchronously:
• Synchronously, in which the script stops and waits
for the server to send back a reply before
continuing.
– Synchronous request in ajax means javascript will stop
processing your program until a result has been
obtained from the server. Until it is processing the
browser is frozen.
– Example if a user needs to signout after check out
something online. In this case it is better to synchronize
ajax call
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str, false);
xmlhttp.send();
}
What is Asynchronous request in AJAX
• AJAX can access the server both synchronously
and asynchronously:
• Asynchronously, in which the script allows the
page to continue to be processed and handles the
reply if and when it arrives.
– Asynchronous ajax will initiate a request to the server
and then return control to the browser. After sometime
you can still manage the result return from
server(means server responds, timedout, error, etc.).
Is AJAX code cross browser compatible?
• Cross-browser compatibility is the ability of a website or web
application to function across different browsers and degrade
gracefully when browser features are absent or lacking.
• Cross-browser compatibility can be defined as the ability of a
website, application or script to support various
web browsers identically.
• Not totally. Most browsers offer a native XMLHttpRequest
JavaScript object, while another one (Internet Explorer)
require to get it as an ActiveX object. Once you have the
object, you're out of the realm of browser differences.
• AJAX code is cross-browser compatible when you
use xmlHttpRequest for different browsers but on
using Jquery.Ajax it creates some issue in legacy IE browsers.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}