Unit - 5 Ajax

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

AJAX Asynchronous 

JavaScript And XML

UNIT - 5

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabi
• AJAX: Ajax Client Server Architecture-XML
Http Request Object-Call Back Methods;
• Web Services: Introduction- Java web services
Basics – Creating, Publishing, Testing and
Describing a Web services (WSDL)-Consuming
a web service, Database Driven web service
from an application – SOAP.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
AJAX Asynchronous JavaScript And XML.
• AJAX is not a new programming language, but a new way to
use existing standards.
• AJAX is the art of exchanging data with a server, and updating
parts of a web page - without reloading the whole page.
• AJAX just uses a combination of:
– A browser built-in XMLHttpRequest object (to request data from a
web server)
– JavaScript and HTML DOM (to display or use the data)
• AJAX allows web pages to be updated asynchronously by
exchanging data with a web server behind the scenes.
• This means that it is possible to update parts of a web page,
without reloading the whole page.
AJAX Asynchronous JavaScript And XML.

• AJAX is a technique for creating fast and dynamic web


pages.
• 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.
• The term AJAX is coined on February 18, 2005, by
Jesse James Garret in a short essay published a few
days after Google released its Maps application.
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)
• AJAX applications are browser- and platform-
independent!
Google Suggest
• AJAX was made popular in 2005 by Google, with Google
Suggest.
• Google Suggest is using AJAX to create a very dynamic
web interface: When you start typing in Google's search
box, a JavaScript sends the letters off to a server and the
server returns a list of suggestions.
How AJAX Works
How AJAX Works
1. An event occurs in a web page (the page is loaded, a
button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web
server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by
JavaScript
AJAX - The XMLHttpRequest Object
• The keystone of AJAX is the XMLHttpRequest
object.
• All modern browsers support the
XMLHttpRequest object.
• The XMLHttpRequest object is used to exchange
data with a server.
• The XMLHttpRequest object can be used to
exchange data with a server behind the scenes.
This means that it is possible to update parts of a
web page, without reloading the whole page.
AJAX - The 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");
s cross-browser compatible when you use xmlHttpRequest for different browsers but on using Jquery.Ajax it creates some issue in legacy IE

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.

var body = XMLHttpRequest.response;


var url = 'somePage.html'; //A local page

function load(url, callback) {


var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.response);
}
}

xhr.open('GET', url, true);


xhr.send('');
}
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
open(method,url,async) Specifies the type of request, the URL, and if the
request should be handled asynchronously or not.

method: the type of request: GET or POST


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

string: Only used for POST requests


<html> <script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
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","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<form>
Enter Name: <input type="text" value="" onkeyup="showHint(this.value);">

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

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status 200: "OK"


403: "Forbidden"
404: "Page not found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")


Callback function
• Callback functions are used to handle
responses from the server in Ajax.
• A callback function can be either a
– named function or
– an anonymous function.
Callback function as an anonymous
function
function start() {
var xmlhttp = new XMLHttpRequest();
var contentDiv = document.getElementById("Content");
xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log(xmlhttp.responseText);
}
}
xmlhttp.setRequestHeader("Content-Type","application/x-www-
form-urlencoded;charset=UTF-8");
xmlhttp.send("FirstName=Nat&LastName=Dunn");
}
Callback function as an named function
1. Create an XMLHttpRequest object in the global scope (outside of
the following two functions).

var xmlhttp = new XMLHttpRequest();

2. Write a function to use as the callback function.

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

You might also like