Friday, August 30, 2013

AJAX Basic Callback Example


AJAX Basic Callback Example

Here is a basic AJAX example which write to demonstrate the callback function call.

Out put -



Once click the “Answer” button the AJAX response as follow.

  
Once click the “Example” button the AJAX response as follow.




Below are the steps for the above example.

1. AjaxBasicCallBack.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX Basic</title>
<style type="text/css">@IMPORT url("css/AjaxBasic.css");</style>
<script>

var xmlhttp;
function loadXMLDoc(url,cfunc)
{
     if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{ // code for IE5, IE6
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
     xmlhttp.onreadystatechange=cfunc;
     xmlhttp.open("GET",url,true);
     xmlhttp.send();
}

function func_myAnswer()
{
     loadXMLDoc("resource/AjaxText.txt",function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("AJAXAnswerDiv").innerHTML=xmlhttp.responseText;
        }
    });
}

function func_myExample()
{
      var txt,x,i;
      loadXMLDoc("resource/ajaxCatlog.xml",function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                 xmlDoc = xmlhttp.responseXML;
                 txt="";
                 x=xmlDoc.getElementsByTagName("examples");
                 for (i=0;i<x.length;i++){
                      txt=txt + x[i].childNodes[0].nodeValue + "<br>";
                 }
                 document.getElementById("AJAXExampleDiv").innerHTML=txt;
            }
     });
}
</script>
</head>
<body>
<h2>AJAX → Asynchronous JavaScript and XML</h2>
<p>* AJAX is a mechanism of exchanging data with a server, and updating parts of a web page, without reloading the whole page.</p>
<p>* What is AJAX ?</p>
<div id="AJAXAnswerDiv" class="redfont"></div>
<p>* What are the examples AJAX using applications ?</p>
<div id="AJAXExampleDiv" class="bluefont"></div>
<br>
<button onclick="func_myAnswer()">Answer</button>
<button onclick="func_myExample()">Example</button>
</body>
</html>

2. AjaxBasic.css

@CHARSET "UTF-8";

body{
font-size: 12px;
font-family: sans-serif;
}
.redfont{
color: red;
}
.bluefont{
color: blue;
}
.h1Gray{
color: gray;
}

3. ajaxCatlog.xml

<?xml version="1.0"?>
<ajaxexamples>
<examples>Goolge Maps</examples>
<examples>Gmail</examples>
<examples>Youtube</examples>
</ajaxexamples>

4. AjaxText.txt

<p class="redfont">AJAX is a technique for creating fast and dynamic web pages</p>