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);

For sending the request to the server open() and send() methods of the XMLHttpRequest object are used.

Method 1 : Open Method


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 –

  1. GET method is more faster than POST method.
  2. GET method is used where security is not an issue.
  3. GET method sends the parameter using the URL.
  4. 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.

  1. POST method is used where we need to send data more securely
  2. POST method does not have size limitation so we can send larger requests than GET method
  3. 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);

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);

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);

In the above example we have sent parameter to the server using the GET method.

Parameter 2 : URL

  1. We can request any type of file from the server.
  2. File requested from the server can be server side scripting file like .php,.asp or any file like .txt,.xml
  3. 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 –


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() method sends the request to the server.

Parameter Explanation
string Parameter is used only when request is of type POST