Asdfasf

Wednesday, October 23, 2013

AJAX Demo

Here is a sample AJAX demo deployed on google app engine. When link is clicked, request is sent to a backend service (http://kulferhat1.appspot.com/time) and result is displayed asynchronously without posting whole page. An ajax loading image is displayed until response is received.

Html code is below


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<script type="text/javascript">
function createXMLHttpRequest(){
  // See http://en.wikipedia.org/wiki/XMLHttpRequest
  // Provide the XMLHttpRequest class for IE 5.x-6.x:
  if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
    throw new Error( "This browser does not support XMLHttpRequest." )
  };
  return new XMLHttpRequest();
}

var AJAX = createXMLHttpRequest();

function handler() {
  
  if(AJAX.readyState == 4 && AJAX.status == 200) {
      var json = eval('(' + AJAX.responseText +')');      
   document.getElementById("resultdata").innerHTML='Success. Result: time => ' + json.time; 
  }else if (AJAX.readyState == 4 && AJAX.status != 200) {
    document.getElementById("resultdata").innerHTML = 'Something went wrong...';
  }
}

function show(){
  AJAX.onreadystatechange = handler;
  AJAX.open("GET", "/time");
  AJAX.send("");
  document.getElementById("resultdata").innerHTML = '<img src="img/Ajax-loader.gif" />';
};

function clearResultData(){
 document.getElementById("resultdata").innerHTML = '';
}
</script>

<body>
  <a href="#" onclick="javascript:show();"> Click here to get time data from the server side</a>
  <a href="#" onclick="javascript:clearResultData();"> Clear </a>
  <div id="resultdata"></div>
</html>


References:
  1. http://www.w3schools.com/ajax/default.asp 
  2. http://code.google.com/p/json-simple/wiki/JSPAndAJAXExamples 
  3. http://loadergenerator.com/example 
  4. http://www.mkyong.com/google-app-engine/google-app-engine-hello-world-example-using-eclipse/

No comments: