Custom Search

Saturday, November 14, 2009

Ajax Note-2

AJAX Note-2
-----------------------------
In this AJAX tutorial we don’t using JavaScript framework JQUERY and JSON. Instead we use JavaScript and XML.

************************************************* (A)
A
*************************************************1
Asynchronous JavaScript + XML

Best example of Ajax is Goggle Maps.

------------------------------------------------------

Ajax is not a technology. It is really several technologies.

* Standards-based presentation using XHTML ans CSS.
* Dynamic display and interaction using the Document Object Model.
* Data interchange and manipulation using XML and XSTL.
* Asynchronous data retrieval using XMLHttpRequest.
* and JavaScript binding everything together.

------------------------------------------------------

'Jasee James’ Model of AJAX.

AJAX applications are made up with 5 parts

1) User Interface ----> XHTML and CSS (Any web browser can display it).

2) DOM (Document Object Model)
The User Interface will have to change when the application runs, that is display new information’s or responds to user input. These changes in the User Interface made using the DOM (Document Object Model).
DOM is a "programming interface" for modifying a web page while it display in the browser.

3) XML
Ajax Applications needs send and receive information’s to and from the Web Server. That information is transmitted in XML format.

4) XMLHttpRequest
This is an object supported by most browsers that allows an application to make a request to the Web Server, receive response and process that response with out interrupting what user is doing.

5) JavaScript
JavaScript ties all the above 4 components together.

a) (JavaScript + XHTML and CSS) JavaScript monitor the 'users interaction' with the 'page' to 'determine' when something need to happened.

b) (JavaScript + XMLHttpRequest) JavaScript Create and activate XMLHttpRequest object to communicate with the Web Server.

c) (JavaScript + XML) JavaScript packages up the information’s to be send to the Web Server in XML format and extract the XML response that come back from the Web Server.

d) (JavaScript + DOM) JavaScript uses the DOM to modify the page currently displayed, thus inform the user that some thing is happened.

------------------------------------------------------

Above is the 'Jasee James' simple model of AJAX. But there are many other ideas or model for AJAX. Many people have many good ideas to improve the simple model of AJAX. For Example,

a) DOM or innerHTML
The standard "DOM" supported by many browsers is also happened to be slow in May browsers. But the nonstandard "innerHTML" supported by many browser happened to be faster than DOM.
The "innerHTML" allow the developer to just drop whole new block of HTML in to the page, the browser will display it with out disturbing the rest of the page.
So "innerHTML" is a good choice to modify the User Interface when the application runs.

b) XML or Plain Text or HTML or JSON
For transmitting messages to and from the Web Server using XML because it is supported by many programming languages.
But Most browsers can red and write XML,but it is slow and heavy process.
We can send data in many other ways....
Sending data as text
Sending a chunk of HTML that can be directly dropped into the page for display.
Sending JavaScript code that can be executed in order to get the information’s contained in the message.

c) XMLHttpRequest is a strong option to send request to Web Server.
Using this XMLHttpRequest object we can send multiple asynchronous requests and deal with responses if when they come.
The limitation of XMLHttpRequest is it only allows sending request to the same Web Server that send the web page currently being displayed.
But this is not a limitation and is used for security purposes.

d) XHTML and CSS or Flash or SVG or XUL
Several AJAX web applications not only using XHTML and CSS to create User Interfaces, instead they using
SVG ---> Scalable Vector Graphic.
XUL ---> Extensible User Interface Language.

Every AJAX applications using JavaScript in some forms ot other to send request in background to Web Server or modify User Interface in the front end. So learn JavaScript to learn AJAX

Every AJAX applications that widely using today deviate from Jessi James vision or model of AJAX in some way or other.
So mastering in AJAX is not only learning a limited set of technology. But also about learning when to use or select one option based on performance, browser compatibility, accessibility and standard.

------------------------------------------------------
AJAX developers must using Firebug.

Use Firebug's "Console"' option to monitor the AJAX request goes on in the background.
Here we can see the AJAX request made in the background by JavaScript to Web Server.
Here we can also see the Response coming back from the Web Server.
------------------------------------------------------
*************************************************2
XMLHttpRequest
==============================

* JavaScript respond to user interactions (on click, on change, on submit, etc) by sending request to Web Server in the background with an object called XMLHttpRequest.

* In order to tie up JavaScript to a particular html tag to respond to user interactions (on click, on change, on submit, etc) we need to make that html tag more identical by using either ID or CLASS attribute of html tag. Then the JavaScript code can take care on this html tag for user interactions (on click, on change, on submit, etc).

* We can use PHP script, Java, Perl, Python, Ruby etc for generating Response for request send by the JavaScript using object called XMLHttpRequest.

* Always try to keep JavaScript code in separate *.js file, that keep readability and accessibility of the page.

==============================
------------------------------------------------------1

* When loading web page we using some JavaScript code to find particular html tags using ID or CLASS attribute of html tag. In the past we used “window.onload“ Event Handler function .But because each document can only have one “window.onload“ Event Handler we need to write multiple scripts for it. We can solve this problem by using “Load” Listener instead of “window.onload“ Event Handler .A single document can have multiple “Load” Listeners associated with it. But the codes require to creating “Load” Listeners vary from browser to browser. A Solution for this is to use a function that contain codes require to creating “Load” Listeners for all popular browsers. We can copy updated version this function from internet. A copy of this function is as follows:

Here argument of this function is another JavaScript function.

function addLoadListener(fn)
{
if (typeof window.addEventListener != ‘undefined’)
{
window.addEventListener(‘load’,fn,false);
}
else if (typeof document.addEventListener != ‘undefined’)
{
document.addEventListener(‘load’,fn,false);
}
else if (typeof window.attachEvent != ‘undefined’)
{
window.attachEvent(‘onload’,fn);
}
else
{
var oldfn = window.onload;
if (typeof window.onload != ‘function’)
{
window.onload = fn;
}
else
{
window.onload = function()
{
oldfn();
fn();
};
}
}
}

------------------------------------------------------2

* Adding Load Listener to page.

addLoadListener(initAjaxTest);

* When the page finish it’s loading the function “initAjaxTest” will be called. So we need to create that function “initAjaxTest” .This function “initAjaxTest” is used for pick out particular html tags using ID or CLASS attribute of html tags from the web page or Document.


function initAjaxTest()
{
//Getting all INPUT tags from the Document and storing in array ‘inputNodes’.
var inputNodes = document.getElementsByTagName(‘input’);

for (var i=0;i<inputNodes.length;i++)
{

//Checking for INPUT tag with CLASS attribute name ‘buttonsubmit1’.
if(inputNodes[i].className = ‘buttonsubmit1’)
{
//Calling function ‘ajaxsubmit’ when clicking on that tag.
inputNodes[i].onClick = ajaxsubmit;
}
}
}

------------------------------------------------------3

When the user click on this tag the function “ajaxsubmit” will be calling. This function send request in background to Web Server, For that this function using XMLHttpRequest object.

function ajaxsubmit()
{
var xhr = new XMLHttpRequest(); //Creating XMLHttpRequest object ‘xhr’.

// This ‘xhr’ object allow to create request and send to the server and receive the response and do what ever you want with it.
// Microsoft Internet explorer 5 and 6 not support to create XMLHttpRequest object this way.
//So using another method to get support of Internet explorer 5 and 6.
}

------------------------------------------------------

Rewriting the code to get support of Microsoft Internet explorer 5 and 6.

function ajaxsubmit()
{
var xhr;

try
{
//Creating XMLHttpRequest object ‘xhr’, common way.
xhr = new XMLHttpRequest();
}
catch(error)
{
//if faille use Microsoft Internet explorer way to create XMLHttpRequest object.
try
(
xhr = new ActiveXObject(‘Microsoft.XMLHTTP’)
}
catch(error)
{
//if faille we can not create XMLHttpRequest object, so store NULL to ‘xhr’.
xhr = NULL;
}

if(xhr != NULL)
{
//if XMLHttpRequest object is created OR browser support AJAX.

// Here we writing the code to send request to Web Server using XMLHttpRequest object ‘xhr’. It is a 3 steps process.

//First step is call XMLHttpRequest object’s “open” method.
//Second step is set up a “onreadystatechange” Event Handler function,. this function is called every time the state of the request is updated.
// Third step is call XMLHttpRequest object’s “send” method.


// 1
xhr.open();


// 2
xhr.onreadystatechange = function()
{

};


// 3
xhr.send();


//return false means we don’t have to submit the form for browsers have AJAX support.
return false;

}

//if xhr is NULL ,that is no XMLHttpRequest object is created ,so we need to submit the form as usual because browser does not support AJAX, so we return true, so the page work with out using AJAX,

return true;

}

------------------------------------------------------4

Above code without comment and code for sending request and handling response using XMLHttpRequest object.


function ajaxsubmit()
{
var xhr;

try
{
xhr = new XMLHttpRequest();
}
catch(error)
{

try
(
xhr = new ActiveXObject(‘Microsoft.XMLHTTP’)
}
catch(error)
{
xhr = NULL;
}

if(xhr != NULL)
{
//if XMLHttpRequest object is created OR browser support AJAX.
// Here we writing the code to send request to Web Server using XMLHttpRequest object ‘xhr’. It is a 3 steps process.
//First step is call XMLHttpRequest object’s “open” method.
//Second step is set up a “onreadystatechange” Event Handler function, this function is called every time the state of the request is updated.
// Third step is call XMLHttpRequest object’s “send” method.

// 1
//The “open” method takes three arguments.
//First argument is the type of the request (POST or GET).
//Second argument is the URL where the request wants to go to.
// for security reason the URL can only be on the same Web Server that the current page that requested from. That is only tried to send request to files that generate and send response on the same Web Server where the requesting page exist, for security reason.
//We can append value with URL and send to Web Server for processing and send response back.
//In URL ’user/display/ajax/1’ we used ‘ajax/1’ to indicate the request handling code or page that it is an AJAX request and handle separate from normal POST and GET request and return separate response. Using this technique we can run the same web application in AJAX supported browser and nor supported browsers. Here “display” is the file or function which handles the request and sends response back.
// Third argument indicate whether the request should be synchronous or asynchronous. Use “true” means asynchronous that is request will be handled in the background with out interrupting the page.

xhr.open(‘POST’,’user/display/ajax/1,true);

// 2
//The “onreadystatechange” Event Handler function used to update User Interface with response from the Web Server.
//This function is called every time when we send request to Web Server with “send” method and this function update with status of the request.

// Ajax requests go through number of ready states as it progresses.
// Here “readyState” and “status” are properties or member variables of the XMLHttpRequest object ‘xhr’.
//If readyState ==4 indicate request completed.
//If status==200 || status=304 indicate request completed successfully and we can update User Interface.

xhr.onreadystatechange = function()
{

if(xhr.readyState == 4)
{
//Request completed

if(xhr.status==200 || xhr.status=304)
{
//Request completed successfully and we can update User Interface
//Code to update User Interface with new information’s received from the web Server writes here.
// --------//
//--------//
//--------//
}
else
{
//Request completed with failure

}

};


// 3
// The “send” method takes one argument which is the contents of the request.
// Suppose we using AJAX for submit form which contain some fields , then all of the field name and its values are encoded into a string and pass as argument of “send” method.
//This method is used to pass large number of contents with request.
//If we included the contents with URL of the “open” method, then no need to pass it as argument of “send” method, and pass “null” argument in that case.

xhr.send(null);


return false;

}

return true;

}

------------------------------------------------------5

Important Steps for creating AJAX applications

1) Binding an Event Handler
inputNodes[i].onClick = ajaxsubmit;

2) Creating an XMLHttpRequest object.
xhr = new XMLHttpRequest();

3) Send request to the Web Server.
xhr.open(‘POST’,’user/display/ajax/1,true);
xhr.send(null);


4) Keep track of request status
xhr.onreadystatechange = function()
{

if(xhr.readyState == 4)
{
//Request completed

if(xhr.status==200 || xhr.status=304)
{
//Request completed successfully and we can update User Interface
//Code to update User Interface with new information’s received from the web Server writes here.
// --------//
//--------//
//--------//
}
else
{
//Request completed with failure
}
};

These are the unique elements that make AJAX applications.

------------------------------------------------------6

Complete JavaScript code without comment.


function addLoadListener(fn)
{
if (typeof window.addEventListener != ‘undefined’)
{
window.addEventListener(‘load’,fn,false);
}
else if (typeof document.addEventListener != ‘undefined’)
{
document.addEventListener(‘load’,fn,false);
}
else if (typeof window.attachEvent != ‘undefined’)
{
window.attachEvent(‘onload’,fn);
}
else
{
var oldfn = window.onload;
if (typeof window.onload != ‘function’)
{
window.onload = fn;
}
else
{
window.onload = function()
{
oldfn();
fn();
};
}
}
}


addLoadListener(initAjaxTest);


function initAjaxTest()
{
var inputNodes = document.getElementsByTagName(‘input’);

for (var i=0;i<inputNodes.length;i++)
{

if(inputNodes[i].className = ‘buttonsubmit1’)
{
inputNodes[i].onClick = ajaxsubmit;
}
}
}


function ajaxsubmit()
{
var xhr;

try
{
xhr = new XMLHttpRequest();
}
catch(error)
{

try
(
xhr = new ActiveXObject(‘Microsoft.XMLHTTP’)
}
catch(error)
{
xhr = NULL;
}

if(xhr != NULL)
{
//if XMLHttpRequest object is created OR browser support AJAX.

// 1
xhr.open(‘POST’,’user/display/ajax/1,true);

// 2
xhr.onreadystatechange = function()
{

if(xhr.readyState == 4)
{
//Request completed

if(xhr.status==200 || xhr.status=304)
{
//Request completed successfully and we can update User Interface
// --------//
// --------//
}
else
{
//Request completed with failure
}
};

// 3
xhr.send(null);

return false;
}

return true;
}

------------------------------------------------------
*************************************************3
Server side code and how it response to AJAX requests.
--------------------------------------------------------------------------------

* Server side code only send the required information to browser (JavaScript Code) to update the page, not load the whole page.
* Server side code needs to send response to 'AJAX request' made by the JavaScript Code.
* We need to send the response in a format that the JavaScript Code can easily use to update the current page.

* There are number of choices to send Response back to JavaScript Code.
1) Most common choice currently is JSON which involves sending the data in the format of JavaScript code and JavaScript is grate to deal JavaScript.
2) We can send Response in plane text format and JavaScript red that plane text and update the page based on it.
3) Another choice is XML. That is sending Response to JavaScript in XML format.

===========================================
Example of Sending Response to JavaScript in XML format.
------------------------------------------------------------------------------------

* First create a PHP script that send contents to JavaScript in XML format.

<?php
header('content-type: text/xml');
echo '<?xml version="1.0" encoding="utf-8" ?>';
?>
<employee>

<?php foreach( $rows as $row){ ?>
<name> <?php echo $row['name']; ?> </name>
<age> <?php echo $row['age']; ?> </age>
<place> <?php echo $row['place']; } ?> </place>

</employee>

* Save this file with *.php extension.
* Then write JavaScript code to read this XML response and update the web page (user interface).

===========================================================
Example of JavaScript code to read this XML response and update the web page
--------------------------------------------------------------------------------------------------------------------


------------------------------------------------------


------------------------------------------------------
************************************************* (B)
B
*************************************************AJAX Example-1
AJAX Example - URL Preview using AJAX
------------------------------------------------------ Html code
<html>
<head>
<title>Smart Ajax Links</title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<script src="script.js" type="text/javascript">
</script>
</head>
<body>
<h2>A Gentle Introduction to JavaScript</h2>
<ul>
<li><a href="jsintro/2000-08.html">August article</a></li>
<li><a href="jsintro/2000-09.html">September article</a></li>
<li><a href="jsintro/2000-10.html">October article</a></li>
<li><a href="jsintro/2000-11.html">November article</a></li>
</ul>
<div id="previewWin"> </div>
</body>
</html>

------------------------------------------------------ Ajax code with comment

window.onload = initAll; //onload call the function "initAll"
var xhr = false; //global variable.
var xPos, yPos; //global variables for X and Y position.


function initAll() {
var allLinks = document.getElementsByTagName("a");

for (var i=0; i< allLinks.length; i++) {
allLinks[i].onmouseover = showPreview; //OnMouseOver call the function "showPreview"

}
}


//This "showPreview" function called based on event.
//The event is automatically passed to function as argument
//So no need to specify argument "evt" in the function call

function showPreview(evt) {
if (evt) {
var url = evt.target; //here target is the url or href of the article
}
else {
evt = window.event; //if event not passed automatically
var url = evt.srcElement;//Source element ie, url of the article
}
xPos = evt.clientX; //X cordinate from where event occure.
yPos = evt.clientY; //Y cordinate from where event occure.

////**** Actual AJAX Request code Start here ****////

if (window.XMLHttpRequest) {
//means if the browser have 'window.XMLHttpRequest',then create a XMLHttpRequest object 'xhr'.
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
//Internet Explorer methode to create a XMLHttpRequest object 'xhr'.
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
//If XMLHttpRequest object 'xhr' successfully created
xhr.onreadystatechange = showContents; //OnReadyStateChange call the function "showContents" to handle the response coming back from the server.
xhr.open("GET", url, true); //Opening a request to send to server
xhr.send(null); //To send that opened request to server
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
return false;

////**** AJAX Request code End here ****////
}



function showContents() {

////**** Actual AJAX Response code Start here ****////

if (xhr.readyState == 4) {

if (xhr.status == 200) { //If request status is OK.if not working change "200" to "0" and try again.

var outMsg = xhr.responseText; //Text version of XMLHttpRequest
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}

var prevWin = document.getElementById("previewWin");
prevWin.innerHTML = outMsg;
prevWin.style.top = parseInt(yPos)+2 + "px"; // Convert to integer and add "px" to end,example 25px.
prevWin.style.left = parseInt(xPos)+2 + "px";
prevWin.style.visibility = "visible";
prevWin.onmouseout = function() {
document.getElementById("previewWin").style.visibility = "hidden";
}
}

////**** Actual AJAX Response code End here ****////
}

------------------------------------------------------ Ajax code without comment -- script.js

window.onload = initAll;
var xhr = false;
var xPos, yPos;

function initAll() {
var allLinks = document.getElementsByTagName("a");

for (var i=0; i< allLinks.length; i++) {
allLinks[i].onmouseover = showPreview;
}
}

function showPreview(evt) {
if (evt) {
var url = evt.target;
}
else {
evt = window.event;
var url = evt.srcElement;
}
xPos = evt.clientX;
yPos = evt.clientY;

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
return false;
}

function showContents() {

if (xhr.readyState == 4) {

if (xhr.status == 200) {

var outMsg = xhr.responseText;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}

var prevWin = document.getElementById("previewWin");
prevWin.innerHTML = outMsg;
prevWin.style.top = parseInt(yPos)+2 + "px";
prevWin.style.left = parseInt(xPos)+2 + "px";
prevWin.style.visibility = "visible";
prevWin.onmouseout = function() {
document.getElementById("previewWin").style.visibility = "hidden";
}
}
}

------------------------------------------------------ CSS code

li a {
text-decoration: none;
font-weight: bold;
}

li a:hover {
text-decoration: underline;
}

h2, ul {
font-family: Georgia, "Times New Roman", Times, serif;
}

li {
list-style-type: none;
}

#previewWin {
background-color: #FF9;
width: 150px;
height: 200px;
font: .6em arial, helvetica, sans-serif;
padding: 5px;
position: absolute;
visibility: hidden;
border: 1px #CC0 solid;
overflow: hidden;
}

#previewWin h1, #previewWin h2 {
font-size: 1.0em;
}

------------------------------------------------------
************************************************* (C)
C
*************************************************
AJAX "Request" and "Response" Code
------------------------------------------------------AJAX Request Code
/*
Code snippet to create a new Ajax request
This code needs to be dropped into a function

Requires:
- Variable xhr to be declared globally
- A function called showContents to handle the completed request
(Or modify onreadystate assignment to use the correct function)
- The variable url needs to be set prior to this code
*/

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}

------------------------------------------------------AJAX Response Code

/*
Code snippet to handle a completed Ajax response
This code needs to be dropped into a function
*/

if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseText;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}

// Do something here with outMsg
}

------------------------------------------------------
*************************************************(D)
D
*************************************************AJAX Example 2
AJAX Example - Goggle suggest - Using XML file

------------------------------------------------------ Html code

<html>
<head>
<title>Auto-fill states</title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<script src="script.js" type="text/javascript">
</script>
</head>
<body>
<form action="#">
Please enter your state:<br />
<input type="text" id="searchField" autocomplete="off" /><br />
<div id="popups"> </div>
</form>
</body>
</html>

------------------------------------------------------ CSS code

body, #searchField {
font: 1.2em arial, helvetica, sans-serif;
}

#popups {
position: absolute;
}

#searchField.error {
background-color: #FC0;
}

div.suggestions {
background-color: #FFF;
padding: 2px 6px;
border: 1px solid #000;
}

div.suggestions:hover {
background-color: #69F;
}

------------------------------------------------------ Ajax code -- script.js

window.onload = initAll;
var xhr = false;
var statesArray = new Array();

function initAll() {
document.getElementById("searchField").onkeyup = searchSuggest;

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = setStatesArray;
xhr.open("GET", "us-states.xml", true);
xhr.send(null);
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
}

function setStatesArray() {
if (xhr.readyState == 4) {

if (xhr.status == 200) {
if (xhr.responseXML) {
var allStates = xhr.responseXML.getElementsByTagName("item");
for (var i=0; i<allStates.length; i++) {
statesArray[i] = allStates[i].getElementsByTagName("label")[0].firstChild;
}
}
}
else {
alert("There was a problem with the request " + xhr.status);
}
}
}

function searchSuggest() {
var str = document.getElementById("searchField").value;
document.getElementById("searchField").className = "";
if (str != "") {
document.getElementById("popups").innerHTML = "";

for (var i=0; i<statesArray.length; i++) {
var thisState = statesArray[i].nodeValue;

if (thisState.toLowerCase().indexOf(str.toLowerCase()) == 0) {
var tempDiv = document.createElement("div");
tempDiv.innerHTML = thisState;
tempDiv.onclick = makeChoice;
tempDiv.className = "suggestions";
document.getElementById("popups").appendChild(tempDiv);
}
}
var foundCt = document.getElementById("popups").childNodes.length;
if (foundCt == 0) {
document.getElementById("searchField").className = "error";
}
if (foundCt == 1) {
document.getElementById("searchField").value = document.getElementById("popups").firstChild.innerHTML;
document.getElementById("popups").innerHTML = "";
}
}
}

function makeChoice(evt) {
var thisDiv = (evt) ? evt.target : window.event.srcElement;
document.getElementById("searchField").value = thisDiv.innerHTML;
document.getElementById("popups").innerHTML = "";
}

------------------------------------------------------ Xml code

<?xml version="1.0"?>
<choices xml:lang="EN">
<item>
<label>Alabama</label>
<value>AL</value>
</item>
<item>
<label>Alaska</label>
<value>AK</value>
</item>
<item>
<label>Arizona</label>
<value>AZ</value>
</item>
<item>
<label>Arkansas</label>
<value>AR</value>
</item>
<item>
<label>California</label>
<value>CA</value>
</item>
<item>
<label>Colorado</label>
<value>CO</value>
</item>
<item>
<label>Connecticut</label>
<value>CT</value>
</item>
<item>
<label>Delaware</label>
<value>DE</value>
</item>
<item>
<label>Florida</label>
<value>FL</value>
</item>

</choices>

------------------------------------------------------
************************************************* (E)
E
*************************************************
"ResponseXML" and "ResponseText" response types.
----------------------------------------------------------------------------
"ResponseText" is the 'text' that the web server passes back in response from the server.
"ResponseText" --> Return response in Text fomat.

"ResponseXML" is the "object" "XMLDocument" that the webserver passes back in response from the server.
"ResponseXML" return response in XMLDocument Object format.

// xhr.responseText return requested 'colors.xml' file in Text format.
// xhr.responseXML return requested 'colors.xml' file in XMLDocument Object format.

If we using "ResponseText" response type, then we can easily access the elements or tags in the requested 'colors.xml' xml file using JavaScript functions 'getElementById' and 'getElementByTagName' etc--.And we can see elements using DOM inspector.

If we using "ResponseXML" response type, then we can also access the elements or tags in the requested 'colors.xml' xml file using JavaScript functions 'getElementById' and 'getElementByTagName' etc--.And we can not see elements using DOM inspector, because reponse is an XMLDocument object.

* Here client requesting an XML file in the server using JavaScript. Then the server send the requested XML file to JavaScript as response. Then the JavaScript accept the response in "ResponseXML" and "ResponseText" response format.

* Or can use "JSON" instead of "ResponseXML" and "ResponseText".

* There are number of choices to send Response back to JavaScript Code.
1) Most common choice currently is JSON which involves sending the data in the format of JavaScript code and JavaScript is grate to deal JavaScript.
2) We can send Response in plane text format (ResponseText) and JavaScript red that plane text and update the page based on it.
3) Another choice is XML. That is sending Response to JavaScript in XML format (ResponseXML).

------------------------------------------------------ Html code

<html>
<head>
<title>A Simple Ajax Script</title>
<script src="script.js" type="text/javascript">
</script>
</head>
<body>
<p><a id="requestXML" href="#">Request an XML file as XML</a></p>
<p><a id="requestText" href="#">Request an XML file as text</a></p>
<div id="updateArea"> </div>
</body>
</html>

------------------------------------------------------ ajax code -- with comment -- script.js

window.onload = initAll; //onload call the function "initAll"
var xhr = false; //global variable
var textRequest; //global variable

function initAll() {
document.getElementById("requestText").onclick = function() {
//anonymous function - function have no name
textRequest = true;
makeRequest(); //calling the function "makeRequest"
return false;
}
document.getElementById("requestXML").onclick = function() {
//anonymous function - function have no name
textRequest = false;
makeRequest(); //calling the function "makeRequest"
return false;
}
}

function makeRequest() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
//onreadystatechange calling function "showContents" to handle server response
xhr.onreadystatechange = showContents;
//Means JavaScript send the request to server that please give me the file called 'colors.xml'.
//Server sends the 'colors.xml' xml file back as "ResponseXML" or "ResponseText" response format.
xhr.open("GET", "colors.xml", true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}

function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//responses xhr.responseText and xhr.responseXML
// xhr.responseText return 'colors.xml' file in Text format.
// xhr.responseXML return 'colors.xml' file in XMLDocument Object format.

var outMsg = (textRequest) ? xhr.responseText : xhr.responseXML;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
}

--------------------------- Ajax code -- without comment -- script.js

window.onload = initAll;
var xhr = false;
var textRequest;

function initAll() {
document.getElementById("requestText").onclick = function() {
textRequest = true;
makeRequest();
return false;
}
document.getElementById("requestXML").onclick = function() {
textRequest = false;
makeRequest();
return false;
}
}

function makeRequest() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", "colors.xml", true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}

function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 0) {
var outMsg = (textRequest) ? xhr.responseText : xhr.responseXML;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
}

------------------------------------------------------ XML code

<?xml version="1.0"?>
<colors xml:lang="EN">
<color>
<name>Aqua</name>
<value>#00FFFF</value>
</color>
<color>
<name>Azure</name>
<value>#F0FFFF</value>
</color>
<color>
<name>Black</name>
<value>#000000</value>
</color>
<color>
<name>Blue</name>
<value>#0000FF</value>
</color>
<color>
<name>Brown</name>
<value>#A52A2A</value>
</color>
<color>
<name>Crimson</name>
<value>#DC143C</value>
</color>
<color>
<name>Cyan</name>
<value>#00FFFF</value>
</color>
<color>
<name>Gold</name>
<value>#FFD700</value>
</color>

</colors>

------------------------------------------------------
*************************************************

No comments:

Post a Comment