Send POST data in JavaScript using XMLHTTPRequest

On the web, it is often necessary to send HTTP requests with post data. In this article, you will learn how to send post data in JavaScript using the XMLHTTPRequest object.

The XMLHTTPRequest is a built-in JavaScript object that allows us to make HTTP requests. You can see that it has the word “XML”. But actually it can operate with any type of data.

Here, we are going to see a simple example of sending post data with the help of the XMLHTTPRequest JavaScript object.

To send post data in JavaScript with XMLHTTPRequest, first, we have to create an XMLHTTPRequest object:

 var http = new XMLHttpRequest();

After that initialize it with the open() method with the request URL. We also pass the method “post” and set the asynchronous to true. Below is the code:

http.open("POST", "login_request.php", true);

Now set the content type urlencoded using the setRequestHeader method:

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

After that check the readyState and get the data back from the requested URL using the read-only XMLHttpRequest property responseText:

http.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
     console.log(this.responseText);
  }
};

Now it’s time to send our URL formatted data. In our example, we are sending username and password:

http.send("username=minaki536&password=Ak5K#[email protected]");

The complete JavaScript code is given below:

var http = new XMLHttpRequest();
http.open("POST", "demo_post2.asp", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("content").innerHTML = this.responseText;
  }
};

http.send("username=minaki536&password=Ak5K#[email protected]");

So we have successfully able to send post data using the XMLHTTPRequest in JavaScript.

In our example, we have sent the content type in the form of urlencoded string. But, XMLHTTPRequest supports multiple data formats. We just need to define the content type in the setRequestHeader method.

Also, read:

Below is an example to send data with content type JSON:

http.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

Well, there are more types supported by XMLHTTPRequest setRequestHeader() method. URL formatted and JSON type is most popular and used by developers widely.

Leave a Reply

Your email address will not be published. Required fields are marked *