stefan22
8/6/2017 - 6:50 PM

Ajax Single Ajax utility and click event

Ajax Single Ajax utility and click event

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <!-- <script type="text/javascript" src="/ajax-util.js"></script> -->
   <!-- <script type="text/javascript" src="/script.js"></script> -->
   <title>Practice test</title>
<script type="text/javascript">
(function(global) {

//namespace to attach things to global
var ajaxScatola = {};

//return HTTP Request Obj/ not avail to global
function getRequestObject() {
   if(window.XMLHttpRequest) {
      return new XMLHttpRequest();
   }//if
   else if(window.ActiveXObject) {
      //old IE
      return new ActiveXObject("Microsoft.XMLHTTP");
   }//else
   else {
      global.alert("Ajax is not supported");
      return null;
   }

}//getRequestObject

//Ajax GET request 
ajaxScatola.sendGetRequest = function(requestUrl, responseHandler) {
      //get request obj
      var request = getRequestObject();
      //onreadystate - when server comesback with response we call handleResponse
      request.onreadystatechange =
         function() {
            handleResponse(request, responseHandler);
         };
         //then open GET
         request.open("GET", requestUrl, true);
         request.send(null);  //for POST only
};//fn


//Only calls user provided responseHandler
function handleResponse(request, responseHandler) {
   if((request.readyState == 4) &&
      (request.status == 200)) {
      responseHandler(request);
   }//if
}//fn
 

//Expose utility to global object ot use it
global.FacingOutAjax = ajaxScatola;



})(window);    
</script>

</head>
<body>
   <h1 id="title">ajax test</h1>

   <p>
      <button>
         Say hello to someone on the Server!
      </button>
   </p>

   <div id="content">
      
   </div>

<script type="text/javascript">
//Event handler
document.addEventListener('DOMContentLoaded', function(e) {
   document.querySelector('button').
   addEventListener('click', function() {
debugger;
      //call server to get name
      FacingOutAjax.sendGetRequest("/name.txt", function(request) {
               var name = request.responseText;
               console.log(name);
               console.log(request);
               document.querySelector('#content')
              .innerHTML = "<h2>Hello " + name + "!";
            

            });


   }); //click event


}); //DOMContentLoaded  

   
</script>
</body>
</html>