How AJAX works?
AJAX communicates with the server using XMLHttpRequest object. Let’s try to understand the flow of ajax or how ajax works by the image displayed below.
As you can see in the above example, XMLHttpRequest object plays a important role.
- HTTP Request is sent to the server by XMLHttpRequest object.
- Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
- Data is retrieved.
- Server sends XML data or JSON data to the XMLHttpRequest callback function.
- HTML and CSS data is displayed on the browser.
- HTML/XHTML and CSS:These technologies are used for displaying content and style. It is mainly used for presentation.
- DOM:It is used for dynamic display and interaction with data.
- XMLHttpRequest:For asynchronous communication between client and server. For more visit next page.
1.AJAX XMLHttpRequest Object – Create, Send & Get Response
XMLHttpRequest object is an API for fetching any text base format data, including XML without user/visual interruptions. All most all browser platform support XMLHttpRequest object to make HTTP requests.
- Define instance of this XMLHttpRequest object:Create new instance of the XMLHttpRequest object, using new keyword,
- Initialize open() method:Now we can initialize open() method along with required parameter and optional parameter.
- Request send using send() method:Finally send() method execute to send it along with above specified parameters.
- onreadystatechange Event To Set Callback Function:Before you calling send method, Using onreadystatechange event to set callback (handler) function to be executed when the status of the request changes
2.AJAX XMLHttpRequest Methods
- setRequestHeader:After requested URL open, use setRequestHeader() method, to provide any optional HTTP headers for the request.
- abort:abort() method used to abort the request
- getResponseHeader:getResponseHeader() method used to get the value of the specified HTTP header.
3.AJAX XMLHttpRequest Properties
- onreadystatechange:Before you calling send method, Using onreadystatechange event to set callback (handler) function to be executed when the status of the request changes,
- readyState:readyState property returns the status of the request
- status:When a request is received on server, Server return the HTTP status code using status property. for example, status code 200 for Ok, 408 for Request timeout, 404 for Request not found.
responseText Requested response return as a string data as a string object.
- responseXML Requested response return as a XML data as a XML object.
- responseBody This property is use when XHR object created as a ActiveX component (for IE 5 & 6).