Ajax Sending Request
To exchange the data with server we require XMLHttpRequest object. We have studies XMLHttpRequest object in the last chapter.
Consider the following syntax -
xmlhttp.open("GET", "msg.txt", true); xmlhttp.send();
For sending the request to the server open() and send() methods of the XMLHttpRequest object are used.
Table of content
Method 1 : Open Method
open(method,url,async)
open() method specifies the type of request, the URL, and specifies whether the request should be handled asynchronously or not.
Parameter | Explanation |
---|---|
method | Request type : GET or POST |
url | Location of the file on the server |
async | true (asynchronous) or false (synchronous) |
Recommanded Reading : Click here to see complete example
Parameter 1 : GET or POST Method :
Below is the reason why we need GET method -
- GET method is more faster than POST method.
- GET method is used where security is not an issue.
- GET method sends the parameter using the URL.
- GET method is used for sending the smaller data to server because URL have limit in different browsers.
Below are some reasons why we should use POST method.
- POST method is used where we need to send data more securely
- POST method does not have size limitation so we can send larger requests than GET method
- POST method is used where cached data is not required, each time we need data from DB.
Recommanded Reading : w3 article on GET and POST methods
Different Cases of GET method :
There are different ways of using the GET method in the Ajax.
Way 1 : Simple GET request
xmlhttp.open("GET", "msg.txt", true); xmlhttp.send();
In the above example we have requested a page from the server using the GET method. There are chances that we may get cached copy of page.
Way 2 : GET request to get non cached copy
xmlhttp.open("GET", "msg.php?p=" + Math.random(), true); xmlhttp.send();
Now when we pass random parameter to the GET method then we will always get fresh copy instead of cached copy.
Way 3 : GET request to send parameter
xmlhttp.open("GET", "msg.php?name=sam", true); xmlhttp.send();
In the above example we have sent parameter to the server using the GET method.
Parameter 2 : URL
- We can request any type of file from the server.
- File requested from the server can be server side scripting file like .php,.asp or any file like .txt,.xml
- This parameter is used to specify the resource on the server.
Parameter 3 : Asynchronous Attribute
If we set the async parameter of the open() method to true like -
xmlhttp.open("GET","execute.php",true);
then request will be sent to server asynchronously. It is added advantages because it makes task easier because all server operations will be done at back end without knowing user.
Method 2 : send Method
send(string)
send() method sends the request to the server.
Parameter | Explanation |
---|---|
string | Parameter is used only when request is of type POST |