AJAX stands for Asynchronous JavaScript and XML.
AJAX is not a Programming Language. It helps us to update a part of web page without re-loading the entire webpage. It is used to exchange data with server in the background asynchronously.
Asynchronous means that the script will send a request to the server, and continue its execution without waiting for the reply. And when the response comes, it takes necessary action like updating the web page with data. This gives a the user a rich experience with web page.
AJAX is achieved with the help of object called ‘XMLHttpRequest’. This object is used to send and receive data from server. This object is built in Browser object.
Once the data is received from server, it is displayed to user with help of HTML DOM(Document Object Model) and Javascript.
HTML DOM can be used to access all elements of HTML and change their content.
Let us know more about how a request can be passed to server using XMLHttpRequest object.
Syntax for XMLHttpRequest object is
- variable = new XMLHttpRequest();
- var objXHttp = new XMLHttpRequest(); //creates a new XMLHttpRequest
Properties and methods of XMLHttpRequest
Let us look into few important properties and methods of XMLHttpRequest object:
Methods
Open(method, url, async, user, psw) specifies the request
The last two parameters User and password are optional
The first parameter methods will have either GET/POST depending on the scenario/requirement
Get is simpler and faster and used in most cases.
Post can be used when there is a large amount of data to sent to server/ for sending user input.
Post is more robust and secure and doesn’t have any size limitation when compared to GET.
- Send() is used to send a request to server. This is used for GET requests.
- Send(string) is used to send a request to server. This is used to POST requests.
Properties
onreadystatechange: This Property defines the method to be called when ready state of the XMLHttpRequest changes
readyState holds the status of XMLHttpRequest,
- request not initialized
- server connection established
- request received
- processing request
- request finished and response is ready
So we can use this property to check if the response is ready or not.
The condition objXHttp.readyState == 4 if true implies that response is ready.
Status returns the status-number of request
A few values of status along with description are given below,
- 200 implies ok
- 403 implies “Forbidden”
- 404 implies “Not Found”
- Similarly, status==200 if true implies the status is ok for request.
responseText returns the response data as a string
Two Considerations which are important to be noted are,
Join the conversation! Your thoughts help the community grow.