Friday, August 30, 2013

AJAX Basic Example – responseText


Ajax Basic Example – responseText

Here is a basic AJAX example which write to demonstrate get the response by text.

Out put -


Once click the “Answer” button the AJAX response as follow.
Below are the steps for the above example.

1. AjaxBasicResponseText.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 - ResponseText</title>
<style type="text/css">@IMPORT url("css/AjaxBasic.css");</style>
<script>
function loadXMLDoc(){
      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");
     }
   
      xmlhttp.onreadystatechange=function(){
         if(xmlhttp.readyState==4 && xmlhttp.status==200){
             document.getElementById("whatAJAXDiv").innerHTML=xmlhttp.responseText;
         }
     }
      xmlhttp.open("GET","resource/AjaxBasic.txt",true);
      xmlhttp.send();
}
</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="whatAJAXDiv" class="bluefont"></div>
<br>
<button onclick="loadXMLDoc()">Answer</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. AjaxBasic.txt

<p class="redfont">AJAX is a technique for creating fast and dynamic web pages</p>
Examples of applications using AJAX:<br>
&nbsp;&nbsp;*&nbsp;Google Maps,<br>
&nbsp;&nbsp;*&nbsp;Gmail,<br>
&nbsp;&nbsp;*&nbsp;Youtube<br>



Thursday, August 29, 2013

AJAX Tutorial


AJAX Tutorial

AJAX → Asynchronous JavaScript and XML.

AJAX is a mechanism of exchanging data with a server, and updating parts of a web page, without reloading the whole page.

* AJAX is a technique for creating fast and dynamic web pages.

Examples of applications using AJAX:
   * Google Maps,
   * Gmail,
   * Youtube


Browser
Internet
Server
An event Occurs
* Create an XMLHttpRequest Object
* Send Http Request




-------------------------------------->


* Process HttpRequest

* Create a response and send data back to the browser.
* Process the returned data using javaScript
* Update Page Content

<-------------------------------------

XMLHttpRequest object - to exchange data asynchronously with a server
JavaScript / DOM - to display/interact with the information

The XMLHttpRequest Object -

The XMLHttpRequest object is used to exchange data with the server and update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object
All modern browsers have a built-in XMLHttpRequest object.

Syntax : variable = new XMLHttpRequest();
Send a request to a server.
Use the open() and send() methods of the XMLHttpRequest object:

Syntax :
                variable = xmlhttp.open(method,url,async); // e.g. open("GET","ajax-info.txt",true);
                xmlhttp.send();

method : the type of request: GET or POST
url : the location of the file on the server . This can be a any kind of file.
async : true (asynchronous) or false (synchronous)

                send(string) : string, only used for the POST request.


Asynchronous - True | False

Many of the tasks performed on the server are very time consuming.
Before AJAX, this operation could cause the application to hang or stop.
With AJAX, the JavaScript does not have to wait for the server response, it can execute other scripts while waiting for server response and deal with the response when the response ready .

async = true : When using async=true, specify a function to execute when the response is ready in the onreadystatechange event.

xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4 && xmlhttp.status==200){
       document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","ajax-info.txt",true);
xmlhttp.send();

async = false : is not recommended, but for a few small requests this can be ok.

Please note that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note: When you use async=false, do NOT write an onreadystatechange function. Just put the code after the send() statement:
    xmlhttp.open("GET","ajax-info.txt",false);
    xmlhttp.send();
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Server Response -

To get the response from the server, can use the responseText or responseXML property.

responseText : get the response data as a string
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

responseXML : get the response data as XML data

The onreadystatechange event -

The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
 
Three important properties of the XMLHttpRequest object:
 
onreadystatechange : Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState : Holds the status of the XMLHttpRequest. Changes from 0 to 4:
                        0: request not initialized
                        1: server connection established
                        2: request received
                        3: processing request
                        4: request finished and response is ready
status 200 : "OK"
                      404: Page not found
*** When readyState is 4 and status is 200, the response is ready.

Note: The onreadystatechange event is triggered five times (0-4), one time for each change in readyState.

Using a Callback Function

A callback function is a function passed as a parameter to another function.
* If you have more than one AJAX tasks, should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
* The function call should contain the URL and what to do on onreadystatechange (which is probably different for each call):

Thursday, August 22, 2013

jQuery Example 01 ( HTML Form selectors )


jQuery Example 01 ( HTML Form selectors )

jQuery has many form selectors to access the form elements more easily and efficiently.
Here I give the simple example of a HTML for with the fields of text box, radio button, drop down list ( select option ), text area and file element.

This example handle the form input validations by using jQuery capabilities. First I show the out puts and then show the html, css, and jQuery js which wrote to complete this example.

1) Display Registration Form



2) Display Registration Form ( with form elements validation )





















3) Display Registration Form ( with the enter input elements valies )



4) HTML file

<!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">
<style type="text/css">@IMPORT url("css/jQueryExample01.css");</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="JQueryJS/jQueryExample01.js"></script>
</head>
<body>

<div id="divHeader" class="headerfont columnTopPadding">&nbsp;&nbsp;User Registration Form</div>
<div id="registration_info" style="display:none;">
<p id="msg" class="fontcolorblue">
</div>
<div id="content" class="divTable">

<!-- Text Box -->
<div class="divRow">
<div class="divColumn">First Name</div>
<div class="divColumn">
<input type="text" id="firstname" size="20" maxlength="20" class="border"/>
<label for="firstname" class="errorfontred" id="errfirstname" style="display:none">Enter your first name correctly</label>
</div>
</div>
<div class="divRow">
<div class="divColumn">Last Name</div>
<div class="divColumn">
<input type="text" id="lastname" size="20" maxlength="20" class="border"/>
<label for="lastname" class="errorfontred" id="errlastname" style="display:none">Enter your last name correctly</label>
</div>
</div>
<div class="divRow">
<div class="divColumn">Contact Number</div>
<div class="divColumn">
<input type="text" id="contactno" size="20" maxlength="20" class="border"/>
<label for="contactno" class="errorfontred" id="errcontactno" style="display:none">Enter your contact number correctly</label>
</div>
</div>
<!-- Radio Button -->
<div class="divRow">
<div class="divColumn">Sex</div>
<div class="divColumn">
<input type="radio" name="sex" value="Male" checked="checked">Male&nbsp;&nbsp;
<input type="radio" name="sex" value="Female">Female
</div>
</div>
<!-- Drop down list -->
<div class="divRow">
<div class="divColumn">Age Group</div>
<div class="divColumn">
<select id="ageGroup" name="ageGroup" class="border" >
<option value="0">Please select</option>
<option value="21-30">21-30</option>
<option value="31-40">31-40</option>
<option value="41-50">41-50</option>
</select>
<label for="ageGroup" class="errorfontred" id="errageGroup" style="display:none">Select the age group</label>
</div>
</div>
<!-- File -->
<div class="divRow">
<div class="divColumn">File to upload</div>
<div class="divColumn">
<input type="file" id="file" class="border"/>
</div>
</div>
<!-- text area -->
<div class="divRow">
<div class="divColumn">Description</div>
<div class="divColumn">
<textarea id="description"cols="40" rows="10" class="border"></textarea>
<label for="description" class="errorfontred" id="errdescription" style="display:none">Please describe your self</label>
</div>
</div>
<!-- Buttons -->
<div class="divRow">
<div class="divColumn columnTopPadding"><button id="reset">Reset</button></div>
<div class="divColumn columnTopPadding"><button id="submit">Submit</button></div>
</div>
</div>
</body>
</html>


5) CSS file

body{
background-color: lightblue; color: black;
font-family: Verdana; font-size: 12px; font-style: normal;
}
.divTable{
width: 50%; display:block; padding-top:10px;
padding-bottom:10px; padding-right:10px; padding-left:10px;
}
.divRow{
width: 99%; display:block;
}
.divColumn{
float: left; width: 48%; display:block;
padding-top:5px; padding-bottom:5px;
}
.columnTopPadding{
padding-top: 10px;
}
.border{
border: 1px; border-style: solid; border-color: blue; color: black;
}
.errorborder{
border-color: red; border: 2px;
}
.headerfont{
color: blue; font-size: 16px;
}
.fontcolorblack{
color: black;
}
.fontcolorblue{
color: blue;
}
.errorfontred{
color: red;
}


6) jQuery JS file

$(function(){
 
  $("#reset").click(function(){
      $("#firstname").val("");
      $("#lastname").val("");
      $("#contactno").val("");
      $('input:radio[name=sex]').filter('[value=Male]').prop('checked', true);
      $("#ageGroup").val("0");
      $('input:file').val("");
      $('textarea').val("");
  });

  $("#submit").click(function(){
     
     var message = "<table width=\"300px\" border=\"1px\">";
     var count = 0;

     if($('#firstname').val() == ""){
         $("#errfirstname").css({"display":"block"});
         $("#firstname").css({"color":"black","border":"2px solid red"});
     }else{
         $("#errfirstname").css({"display":"none"});
         $("#firstname").css({"color":"black","border":"1px solid blue"});
         count = count + 1; //1
         message = message + "<tr><td width=\"50%\" class=\"fontcolorblack\">&nbsp;First  Name</td><td>&nbsp;:&nbsp;" + $('#firstname').val(); + "&nbsp;</td></tr>";
     }

     if($('#lastname').val() == ""){
          $("#errlastname").css({"display":"block"});
          $("#lastname").css({"color":"black","border":"2px solid red"});
     }else{
          $("#errlastname").css({"display":"none"});
          $("#lastname").css({"color":"black","border":"1px solid blue"});
          count = count + 1; //2
          message = message + "<tr><td width=\"50%\" class=\"fontcolorblack\">&nbsp;Last Name</td><td>&nbsp;:&nbsp;" + $('#lastname').val(); + "&nbsp;</td></tr>";
     }

     if($('#contactno').val() == ""){
          $("#errcontactno").css({"display":"block"});
          $("#contactno").css({"color":"black","border":"2px solid red"});
     }else{
          $("#errcontactno").css({"display":"none"});
          $("#contactno").css({"color":"black","border":"1px solid blue"});
          count = count + 1; //3
          message = message + "<tr><td width=\"50%\" class=\"fontcolorblack\">&nbsp;Contact No.</td><td>&nbsp;:&nbsp;" + $('#contactno').val(); + "&nbsp;</td></tr>";
      }

     if($('input:radio[name=sex]:checked')){
          message = message + "<tr><td width=\"50%\" class=\"fontcolorblack\">&nbsp;Sex</td><td>&nbsp;:&nbsp;" + $('input:radio[name=sex]:checked').val(); + "&nbsp;</td></tr>";
     }

     if($("#ageGroup").val() == "0"){
         $("#errageGroup").css({"display":"block"});
         $("#ageGroup").css({"color":"black","border":"2px solid red"});
     }else{
         $("#errageGroup").css({"display":"none"});
         $("#ageGroup").css({"color":"black","border":"1px solid blue"});
         count = count + 1; //4
         message = message + "<tr><td width=\"50%\" class=\"fontcolorblack\">&nbsp;Age Group</td><td>&nbsp;:&nbsp;" + $('#ageGroup').val(); + "&nbsp;</td></tr>";
     }

     if($('input:file').val() == ""){
          message = message + "<tr><td width=\"50%\" class=\"fontcolorblack\">&nbsp;File Upload</td><td>&nbsp;:&nbsp;No&nbsp;</td></tr>";
     }else{
          message = message + "<tr><td width=\"50%\" class=\"fontcolorblack\">&nbsp;File Upload</td><td>&nbsp;:&nbsp;Yes&nbsp;</td></tr>";
     }

     if($('textarea').val() == ""){
          $("#errdescription").css({"display":"block"});
          $('textarea').css({"color":"black","border":"2px solid red"});
     }else{
          $("#errdescription").css({"display":"none"});
          $('textarea').css({"color":"black","border":"1px solid blue"});
          count = count + 1; //5
          message = message + "<tr><td width=\"50%\" valign=\"top\" class=\"fontcolorblack\">&nbsp;Description</td><td>&nbsp;:&nbsp;" + $('textarea').val(); + "&nbsp;</td></tr>";
     }

     if(count == 5){
          message = message + "</table>";
          $("#registration_info").css("display","block");
          $("#msg").html(message);
     }
});

  //Checks inputs for a-z
  $("#firstname").keypress(function(evt){
       var key =evt.keyCode || evt.which;
       var charCode = (evt.which) ? evt.which : evt.keyCode;
       key = String.fromCharCode( key );
       var CHAR_VALIDATOR = /^([a-zA-Z]+)$/;
       if(!(CHAR_VALIDATOR.test(key) ||charCode==4||charCode== 8 ||charCode==9 )) {
           return false;
       }else{
           $("#errfirstname").css({"display":"none"});
           $("#firstname").css({"color":"black","border":"1px solid blue"});
           return true;
       }
  });

  //Checks inputs for a-z
  $("#lastname").keypress(function(evt){
      var key =evt.keyCode || evt.which;
      var charCode = (evt.which) ? evt.which : evt.keyCode;
      key = String.fromCharCode( key );
      var CHAR_VALIDATOR = /^([a-zA-Z]+)$/;
      if(!(CHAR_VALIDATOR.test(key) ||charCode==4||charCode== 8 ||charCode==9 )) {
           return false;
      }else{
           $("#errlastname").css({"display":"none"});
           $("#lastname").css({"color":"black","border":"1px solid blue"});
           return true;
      }
  });
 
  //Checks inputs for numbers
  $("#contactno").keypress(function(evt){
       var key =evt.keyCode || evt.which;
       var charCode = (evt.which) ? evt.which : evt.keyCode;
       key = String.fromCharCode( key );
       var CHAR_VALIDATOR = /[0-9]/;
       if(!(CHAR_VALIDATOR.test(key) ||charCode==4||charCode== 8 ||charCode==9 )) {
           return false;
       }else{
           $("#errcontactno").css({"display":"none"});
           $("#contactno").css({"color":"black","border":"1px solid blue"});
           return true;
       }
  });

  $('textarea').keypress(function(evt){
      var key =evt.keyCode || evt.which;
      if(key != ""){
          $("#errdescription").css({"display":"none"});
          $('textarea').css({"color":"black","border":"1px solid blue"});
          return true;
     }
  });
 
  $('#ageGroup').click(function(){
       $("#errageGroup").css({"display":"none"});
       $("#ageGroup").css({"color":"black","border":"1px solid blue"});
       return true;
  });
 
  $('#ageGroup').keypress(function(evt){
       var charCode = (evt.which) ? evt.which : evt.keyCode;
       if(charCode==4||charCode== 8 ||charCode==9 ||charCode==37 ||charCode==38   ||charCode==39 ||charCode==40 ){
           $("#errageGroup").css({"display":"none"});
           $("#ageGroup").css({"color":"black","border":"1px solid blue"});
           return true;
        }
   });
});