Wednesday, September 2, 2009

AJAX: The Complete Tutorial Using Java Script

AJAX

Hai Guys, As I was sitting on bench in Organization I thought to write a Complete Article on AJAX , XMLHttpRequest Object and the web policies.


First of all let me introduce what is AJAX.

AJAX is the short for of Asynchronous JavaScript And XML In conventional web application the control of the sending request and handling response are in the hands of Browser. But in AJAX with use of JavaScript XMLHttpRequest Object it gives the complete handling of Sending Request and Handling the responses. Google was apparently the first to realize the power of XMLHttpRequest. With Gmail and Google Maps, they built applications that took advantage of this to provide a user.


AJAX comprises of different web development techniques as follows.

  1. XHTML, CSS for Data Presentations
  2. DOM(Document Object Model) for dynamic display of and interaction with data
  3. XML and XSLT for the interchange, and manipulation and display, of data, respectively
  4. XMLHttpRequest The Core JavaScript Object for asynchronous communication with Server
  5. JavaScript The Client Side Browser language to bring these technologies together

The above all technologies combinely help to create Interactive Rich Internet Applications.


What is XMLHttpRequest.

The XMLHttpRequest is the JavaScript object works as the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, as I mentioned above it was not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.

In the AJAX the data can be returned as text or XML, here in text you can return the Complete HTML file as response if required.Before AJAX people used to Apply this by using IFrame by setting the URL.


XMLHttpRequest Life Cycle:

  1. create an XMLHttpRequest object (or equivalent Active X control in IE)
  2. Set the URL in XMLHttpRequest in which we want to connect;
  3. Set the callback handler javascript method to process response data;
  4. call the send() method, passing in any data to be posted;
  5. Program the callback handler method in such a way that it will process the response in meaningful way.


XMLHttpRequest Life Cycle in Detail:


1. Create the XMLHttpRequest object

It is the first and most straightforward step in AJAX implementation.As simple as any Object creation in any language in Javascript also we will define as follows.

var reqObj = new XMLHttpRequest();

This Object will work with almost all the web browsers other than Internet Explorer (But in later IE releases they started supporting for this..)),

To make the Object Standardized for all the web browsers we can define a method as follows.



 function createXMLHttpRequest() {
    try { return new XMLHttpRequest(); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) {
        alert("XMLHttpRequest not supported");
        return null;
    }
 }

[An Active X control is a type of embeddable Windows program component.]

function createRequestObj() {
       if (window.ActiveXObject) {
          xhr = new ActiveXObject("Microsoft.XMLHttp");
       } else {
          xhr = new XMLHttpRequest();
       }
    }


2. Setting Up the Request URL.

To make a call to the server, we first specify the URL that we want to connect to by the use of open() method in XMLHttpRequest, passing in the request URL.


xhReq.open("get", "studentDeatils.jsp", true);


XMLHttprequest Supports the following methods for making the Requests.


void open(DOMString method, DOMString url);

void open(DOMString method, DOMString url, boolean async);

void open(DOMString method, DOMString url, boolean async, DOMString? user);

void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password);

void setRequestHeader(DOMString header, DOMString value);

void send();

void send (Document data);

void send ([AllowAny] DOMString? data);

void abort();


For Handling the response API supports the following methods.


readonly attribute unsigned short status;

readonly attribute DOMString statusText;

DOMString getResponseHeader(DOMString header);

DOMString getAllResponseHeaders();

readonly attribute DOMString responseText;

readonly attribute Document responseXML;


States of The XMLHttpRequest :

The readyState attribute, is the attribute provides current state of the XMLHttpRequest we made.


const unsigned short UNSENT = 0;

const unsigned short OPENED = 1;

const unsigned short HEADERS_RECEIVED = 2;

const unsigned short LOADING = 3;

const unsigned short DONE = 4;

UNSENT (numeric value 0)

The object has been constructed.

OPENED (numeric value 1)

The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)

All HTTP headers have been received. Several response members of the object are now available.

LOADING (numeric value 3)

The response entity body is being received.

DONE (numeric value 4)

The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

OPENED state has an associated send() flag that indicates whether the send() method has been invoked. It can be either true or false and has an initial value of false.

DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false.


Note that we can POST data to the server (typically in XML format), or for simple cases, we could use GET and append some parameters to the URL. In the latter case, we'd just pass null to the send() method.

We used to pass in a local URL to the site from which the page is loaded. For security reasons:[The Cross URL XMLHttpRequest Will be discussed later. Viz Cross XHR], The Browsers Policies won't let you make an XMLHttpRequest to a URL from a different host to that from which the page was loaded.


3.Process data in the callback handler

As the Name says the call back method will not be executed at once, but rather asynchronously. Once the response came from the Server for every status of XMLHttpRequest.readyState this method will be invoked.

function responseProcessingFunction() {

// state of 4 means request completed

if (xhr.readyState == 4) {

var responseXML = xhr.responseXML;

// ... process the response ...

}

}


The resadyState = 4 means the request is DONE.


Limitation of Ajax

As the name suggests AJAX requires JavaScript Enabled Browsers.If the Browser doesn’t support or disabled the Application will not be running in web browsers. This alone means that AJAX applications will not work in web browsers and devices that do not support JavaScript. For this reason it is not accessible to many typical Web users
This is one of the limitations of the technology but as it’s having so many features the technology has many drawbacks too.

Future of Ajax:

AJAX is an extension of DHTML programming, adding the capability to dynamically send and retrieve data from the web server in response to user actions.The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. Instead, the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities.
AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.Ajax has changed the face of the web forever. Save for some of the browser enhancements and a few other technologies, I dare to say that it’s had the most significant impact on the way we use the internet in its short life.


A Simple practical Example in JSP.


AjaxExample.html



<script language="JavaScript">
    function concatName()
    {
      // Create the XML request 
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;
      var URL="concat.jsp?firstName="+firstName+"&lastName="+lastName;
      xmlReq = null;
      if(window.XMLHttpRequest)
         xmlReq = new XMLHttpRequest();
      else if(window.ActiveXObject)               
      xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
      if(xmlReq==null){
         alert('Failed to Create Request.....')
         return; // Failed to create the request
      }

      // Anonymous function to handle changed request states
      xmlReq.onreadystatechange = function()
         {
             switch(xmlReq.readyState){
              case 0:              // Uninitialized
                      break;
              case 1: // Loading
                      break;
              case 2: // Loaded
                      break;
              case 3: // Interactive
                      break;
              case 4: // Done!
              // Alerting teh response as Text, and processing the responseXML(We are responding         as and XML from Server.)
                      processResponseText(xmlReq.responseText);
                      break;
              default:
                      break;
            }
         }
      // Make the request
      xmlReq.open ('GET', URL, true);
      xmlReq.send (null);
   }

   function processResponseText(responseText){
      var fullName=responseText;
      document.getElementById("concatName").value=fullName;
   }
</script>

AJAX Example

A Simple Concatenation Function Using AJAX First Name +<br/> Last Name -- <input type="button" value="Concatenate Name" onclick="concatName()"> -- ConcatenatedName= <input id="concatName"> </BODY> </HTML>
Concat.jsp
<%
    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");
    String fullName=firstName+" "+lastName;
    <%=fullName%>
    %>

AJAX Example This Page have simple the Concatenating Java Code.Just a replacement of Java Servlet to make the Example Simpler.

Reference:

http://www.javamex.com/tutorials/ajax/xmlhttprequest.shtml

http://www.w3.org/TR/2009/WD-XMLHttpRequest-20090820/

http://www.w3schools.com/Ajax/

And Obviously Google,


Cross XHR

Cross XHR.

Normally the web application make request to the same server. Cross XHR is simply the Cross Domain XMLHttpRequest, which is used to access some other service in different port of the same server, or to any other domain/Servers. Web application technologies commonly apply same-origin restrictions to network requests. These Restrictions prevents a client-side Web application running from one origin retrieving data from another origin, and also limit the amount of unsafe HTTP requests that can be automatically launched toward destinations that differ from the running application's origin which is called as “Same origin policy for JavaScript.


For Example:

You are running your Website in www.mywebsite.com

If you has to make an XHR for other server like www.myothersite.com the XHR.response will as follows in different Browsers.


The Code for AJAX

try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}

xmlHttp.open("POST",”www.myothersite.com” , true);


  • Internet Explorer.

Here it will you a warning that “To help protect your security, Internet Explorer has restricted this file from showing active content that could access your computer. Click here for details.”. After Allowing that you can access the yahoo.com or any server request.

  • Mozilla Firefox & Google Chrome

No Warning or message will be shown but the response (xmlHttp.responseText)

Will be a Zero length string. It shows it stops if the request violates Browser policies.


We can summarize as follows. For a URL (http://mywebsite.com/)

URL

Outcome

Reason

http://mywebsite.com/dir2/other.html

Success

http://mywebsite.com/dir/inner/another.html

Success

https://mywebsite.com/secure.html

Failure

Different protocol

http://mywebsite.com:81/dir/etc.html

Failure

Different port

http://news.company.com/dir/other.html

Failure

Different host


Now our next target is How to Achieve Cross XHR.

W3C has introduced new Specification called Cross-Origin Resource Sharing (CORS).This specification consists of a simple header exchange between client-and-server, and is used by IE8’s proprietary XDomainRequest object as well as by XMLHttpRequest in browsers such as Firefox 3.5 and Safari 4 to make cross-site requests. These browsers make it possible to make asynchronous HTTP calls within script to other domains with GET and POST requests, provided the resources being retrieved are returned with the appropriate CORS headers.


Cross-Origin Resource Sharing (CORS).

It is nothing but adding the Access Control header in the Domain which is need to be accessed using Cross Domain. For example in www.myothersite.com we need to add one header as follows for any access from www.mysite.com Access-Control-Allow-Origin: http://www.myothersite.com


For more details on Access Control please look in the following links.

  1. W3C Cross Domain Documents
  2. Mozilla HTTP Access Control


Hacking Using Cross XHR.

Different Cross XHR approaches in Internet are:

  1. Create one webservice to the other website in the same Server and give to client side using the same domain name.
    1. Yes definitely now it is a server side programming, Nothing to worry about Cross XHR Javascript Policies. It will work Fine.
  2. Using IFrame which connect to other websites and render locally.Use Javascript to handle the IFrame Data.
    1. Here the issue that Javascript will not allow to connect any IFrame in the document which has the different domain Name.Hence this approach will not work.
  3. By Using FlashXmlHttprequest
    1. I have tried the example it was not working. Still the security issues.you can look at the example here
  4. Cross Domain XMLHttpRequest using an IFrame Proxy provided in the dojotoolkit. Dojotoolkit Open here
    1. I haven’t tried this, please try this and let me know.


Reference:

      1. http://www.w3.org/TR/access-control/
      2. https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript
      3. http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
      4. https://developer.mozilla.org/En/HTTP_access_control
      5. www.google.com

Saturday, August 22, 2009

Friday, August 21, 2009

The Benefits of Fasting

The original meaning sawm is to be at rest. We give rest to the gastro-intestinal tract, the sexual organs, the tongue, the eyes and ears, etc. The transit time for a bolus of food from the mouth to the end of the large intestine, called colon, is about 14 hours. This is the period - of 14 hours - during which we fast and withhold any stimulus, reaching the stomach and the digestive system.

In fact, fasting is an additional safety device for the regenerative processes of the body. The repair processes of the body and the brain, including the memory molecules take place when the body is at rest, especially during the stage of deep sleep. Sleeping during Ramadan is much deeper than in other times. Two hours of sleep during Ramadan are more satisfying and refreshing than more hours of sleep otherwise.

Fasting significantly increases deep sleep and reduces the dreaming time, which takes place during the Rapid Eye Movement (REM) sleep. Therefore, it is more beneficial for the elderly to fast because their normal hours of deep sleep in the non-fasted state are much less.

Fasting is a divine prescription, because Allah Himself prescribed it in the Qur’an. Because the Islamic fast does not exceed 14 hours or so, the normal steady state of the body is maintained as a result of coordinated physiological mechanisms. Hence, nearly all the biochemical results in the laboratory are normal.

During fasting, serum magnesium is increased and…
  • Magnesium has cardio-protective effects and it is being used in prevention and treatment of heart attacks.
  • It has anti-platelet properties and prevents extension of the clot.
  • It is a membrane stabilizer acting on the sodium/potassium/calcium flux at the membrane level. Hence, it prevents cardiac and cerebral dysrhythmias.
  • Fasting, through the beneficial effects of magnesium, prevents the formation of atheroma as well as dissolves atheromatous plaques which are responsible for heart attacks and strokes. Hence, fasting takes an active part in the rejuvenating processes of the body through many channels.
  • It increases the fibrinolytic activity of the blood, which leads to prevention and also dissolution of any recent clot.


Ramadan puts a healthy mind into a healthy body. During fasting, there is increased secretion of the growth hormone by the pituitary gland. It is an anabolic hormone for synthesis of proteins and collagen, which produces a positive nitrogen balance. It also stimulates erythropoiesis, as well as collagen synthesis.

During the exercise of fasting, prayers and different spiritual experiences of Ramadan, certain endogenous substances are released by the brain and spinal cord into the body called opioids, which include enkephalins and endorphins. These are responsible for euphoria, tranquility and serenity during such periods.

Endorphins and enkephalins are natural painkillers. Endorphins may be responsible for the "feel nice" effects, experienced by many people after rigorous exercise. Endorphins and enkephalins are derived from beta-lipotropin. On release, it is cleaved to form three major active products: called met-enkephalin, gamma-endorphin, and beta-endorphin.

Beta-endorphin is most active, and is about 20 times as potent as morphine. In addition to their painkilling properties, the narcotic analgesics cause a profound feeling of well-being (euphoria). It is this feeling that is in part responsible for the psychological drive of certain persons who are fasting. Other mechanisms reduce pain sensation by blocking the transmission of pain message to the brain.

To alter the pain sensation, the brain and spinal cord release specialized neurotransmitters called endorphins and enkephalins. These chemicals interfere with pain impulse transmission by occupying the nerve cell receptors, required to send the impulse across the synapse. By making the pain impulse travel less efficiently, endorphins and enkephalins can significantly lessen the perception of pain. In extreme circumstances, they can even make severe injuries nearly painless.

If an athlete is injured during the height of competition, or a soldier injured during a fight, or persons who are fasting, they may not realize they have been hurt, until after the stressful situation has ended! This happens because the brain produces abnormally high levels of endorphins or enkephalins, in periods of intense stress, excitement or fasting.

Fasting and bio-rhythm

Muslims who have been fasting regularly since childhood have been exposed to different sleep/wake and light/darkness cycles on a daily basis in one annual lunar month. Hence, it may be easier for such persons to synchronize at a faster rate their circadian, circa-lunar and circa-annual bio-rhythms, under difficult conditions.

Therefore, it is expected that Muslims who fast regularly would least suffer from jet lag while traveling in a plane from West to East and that health problems in Muslim shift-workers would be minimal. In fact, the central circadian biological clock is located in the suprachiasmatic nucleus of the hypothalamus. It is a cluster of about 10,000 neurons on either side of the mid line, above the optic chiasma about 3 cm behind the eye.

Re-setting proceeds at the rate of 1-2 hours/day to adapt to a reversed shift pattern. There are widespread individual variations in the rapidity of resynchronization. Muslims who fast regularly and who have had disturbed wakefulness/sleep cycles on a daily lunar annual basis, can adapt themselves much faster to different conditions during international travel. This is while crossing time zones and do not suffer from the ill effects of jet lag.

It is also a common observation that as soon as Ramadan is over, normal circadian rhythms are established within the fasted Muslim, with such great rapidity on the first day of the following month of Shawal. This means that `Eid-al-Fitr (Minor Feast) is to be at par with pre-Ramadan levels.

Normally, a period of three weeks is required for resynchronization, among shift workers. As the fasting Muslim attunes himself to resynchronization processes, during the space of just over four weeks in Ramadan, his health problems - as a shift worker - would be negligible. His synchronization processes would be more rapid, whether during Ramadan or any other time.

The Benefits of Long Night Prayers

Moreover, the social contact during tarawih or qiyam (long night prayers) and other social spiritual activities should act as a zeitgeber (from German ‘time-giver’). This is what regulates any desynchronized biological rhythm.

Throughout the year, the average Muslim performs his 5-time daily obligatory prayers, as well as the optional ones. This amounts to gentle physical exercise, involving each and every muscle in the body. During the month of fasting, additional prayers of 8-20 rak`as (physical unit of prayer) are also performed at nights. Approximately, 200 kcals. are utilized during qiyam for the 20 rak`as.

Such additional exercise utilizes any extra calories, ingested at iftar (meal for breaking the fast) approximately 1-2 hours earlier. Simultaneously, the blood glucose is steadily rising in the blood from the ingested nutrients; the circulating glucose is oxidized to CO2 and H20 during the prayers.

The physical movements during qiyam prayers improve flexibility, co-ordination and relaxation response. It also reduces stress-related autonomic responses in normal persons and relieves anxiety and depression. Adrenaline and noradrenalin are secreted during the physical exercise of qiyam. They are responsible for the consequent dynamism, which now combines with the tranquility and the serenity, due to the secretion of enkephalins, endorphins, dynorphins and others.

This makes the night prayers unique in the sense that dynamism is combined in the same individual with serenity, euphoria and dignity. The effects of adrenaline and noradrenaline are apparent, even after long night prayers is over, as evidenced by the continuing activity. In fact, even the thought or intention of performing qiyam prayers is sufficient to activate the sympathetic nervous system. Persons who fast and perform qiyam report feeling much better and healthier.

Repeated and regular movements of the body during prayers improve muscle tone and power, tendon strength, joint flexibility and the cardio-vascular reserve. The body movements help to prevent osteoporosis in the osteoporotic bones of elderly men and post-menopausal women.

The strain put on the forearm, during prostration in lifting the body from the ground, increases the bone mineral content of the forearm. The varying load during the different postures causes a lubricating effect and a protective flow of synovial fluid into the joint cavity. The reinforcement of the calf muscle pump by active ankle movements prevents deep vein thrombosis, which is a common cause of chronic ulcers of the legs in the elderly.

Exercise prevents coronary heart disease, improves carbohydrate tolerance and ameliorates late-onset type 2 diabetes. Growth hormone secretion elevated by fasting is further elevated by exercise of long night prayers. As this hormone is necessary for collagen formation, this may be an important factor in the long delay of the wrinkling of skin for the fasting Muslim who performs qiyam prayers.

Exercise of qiyam improves mood, thought and behavior. Memory for short-term events deteriorates with old age. Prayers improve memory in the elderly, for short-term events, by keeping the memory pathways in the brain open and communicating with each other, especially with constant repetition of the verses from the holy Qur’an and other supplications of Allah’s glory. This also helps to screen the mind from other incoming thoughts.

The repetition of a prayer, supplications of glorification, dhikr (words glorifying Allah) or muscular activity, coupled with passive disregard of intrusive thoughts, causes a relaxation response, leading to lowering of B.P. and decrease in oxygen consumption, as well as a reduction in the heart and respiratory rates.

All these are combined in qiyam prayers, which is an ideal situation for relaxation response, as it combines repeated muscular activity with repetition of words of glorification of Allah and supplications. Thus qiyam puts the mind at ease. Islamic prayers are unique in that tension builds up in the muscles, during the physical movements of prayers, with accompanying adrenaline and noradrenalin. Simultaneously, tension is relieved in the mind due to the spiritual component, assisted by the secretion of enkephalins, endorphins, dynorphins and others.

All those persons who perform qiyam prayers feel more alert and active, even after the age of retirement. They can meet with unexpected challenges of life much better, such as running for a bus! This improves their stamina, self-esteem and self-confidence in being independent.

Saturday, July 25, 2009

Country State Dropdown Data / Java Program to create Country State Database Table Data

Hi,
I have been struggling long time to get the information for the country state Database Table Data and its implementation in My most of the application,
I have searched through net and now i got few data from the site and I have created Java file to generate the SQL Queries.

The Table Structure i have created as Follows.
Country
ID [PK]
NAME [VARCHAR].

State
ID [PK]
NAME [VARCHAR]
COUNTY_ID [PK] Foreign key to Country Table

You can download the java Class file to generate the SQL Queries directly from My Google Docs http://docs.google.com/Doc?docid=0AW0ekoc5wU3rZGYyMnZrZmtfN2NtYnF3dmQ0&hl=en

If you require the SQL File Directly you can download from My Docs as .

I am Thankful to the website http://www.microcosmotalk.com/tech/scripts/ for the datas of countries and States in their site javascipt file.

[I converted Java and sql file to txt format just to upload in Google Docs. :) ]
Hope it will help you out.

Any Concerns Contact :- askeralim@gmail.com