Wednesday 20 March 2013

Ajax calling in javascript


Ajax - Asynchronous JavaScript and XML
Ajax is not a new programming language. But it is a new way to use existing standards.
Ajax is the art of exchanging data with a server, And updating a parts of web page, -without reloading the whole page.
Work flow of Ajax
1. Whenever an event occur browser creates an XMLHttpRequest object and send it to server through internet.
 2. Process HttpRequest, Create response and send back to the browser.
3. Process the returned data using JavaScript and update page.
Request to Server
1.Create an XMLHttpRequest object
For modern browsers, We  have to write like.
Var XMLHttpObj=new XMLHttpRequest();
For old version browsers
Var XMLHttpObj=new ActiveXObject("Microsoft.XMLHTTP");
2. Send a request to server
To send a request to server we use two methods  open() and send() methods of the XMLHttpRequest object
XMLHttpObj.open(“GET”,”URL goes here”,”Asyncronous either true or false”);
XMLHttpObj.send();
We can use GET() or POST().GET is simpler and faster than POST, and can be used in most cases.
However always preferred to use POST(), Because
1. A cached file is not an option
2. Sending a large amount of data to server(POST does not have size limitation)
3. Sending a user input to server(like special chars and numbers) POST is most robust and secure than GET().
If we wanted to send information with the GET,Add the information with url.
xmlhttp.open("GET","url?fname=Henry&lname=Ford",true);
About URL
The url parameter of the open() method, is an address to a file on a server
XMLHttpObj.open(“GET”,”url”,true);
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php
Server Response
To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object
responseText – get the response data as string      assignedvalue=XMLHttpObj. responseText;
responseXML –get the response data as xml data
The onreadystatechange event
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
3 important properties of the XMLHttpObject
1. onreadystatechange    --Stores a function (or the name of a function) to be called automatically each time the readyState property changes
2.ready state ---It holds the XMLHttpRequest
0:request not initialized
1:Server Connection established
2:Request Received
3:Processing Request
4:request finished and response is ready
3.Status
200: ok
404:page not found