Send POST data using a HTTP request

Sometimes the need arises to send POST data in a HTTP request. This is (relativley) simply achieved using XMLHttpRequest (XHR).

To begin with, we create a new XHR instance, along with setting the URL of the thing to send the request to and the POST parameters to send (each separated by an & symbol).

const http = new XMLHttpRequest();
const url = 'get_data.php';
const params = 'lorem=ipsum&name=binny';

We then initialise our newly created request, and set the request header to Content-type: application/x-www-form-urlencoded.'POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

The arguments of open can be found here, but in the above line, we specify the method and URL to send the request to, and then set async to true, to allow the operation to be performed asynchronously. This means we will have to utilise an event listener to do something once the request has been processed. This can be done one of two ways.

  1. Using the standard addEventListener with the event type "load", where transferComplete is the name of the function to be run when the event listener is called.
  2. Using XHR'sĀ onreadystatechange, with the callback being either a normal or anonymous function which is run every time the state is changed. Because of this, we need to check if the state has changed to the type we are looking for, which is done usingĀ readyState .
    readyState has 5 possible values, shown below
    Value State Description
    0 UNSENT Client has been created. open() not called yet.
    1 OPENED open() has been called.
    2 HEADERS_RECIEVED send() has been called, and headers and status are available.
    3 LOADING Downloading; responseText holds partial data.
    4 DONE The operation is complete.

    In this case, we want to only do something when the value is 4 and the HTTP status code is 200 (retrieved using status, and then we can go on to execute our transferComplete function using a neat single line if statement.

The contents of the response can be accessed using responseText, which will either return the textual data received or null if the request failed.

// standard addEventListener
http.addEventListener("load", transferComplete);

// XHR's onreadystatechange
http.onreadystatechange = if (http.readyState == 4 && http.status == 200) transferComplete();

Once all this is done and out of the way, we can then go on to actually make the request.


Complete code:

const http = new XMLHttpRequest();
const url = 'get_data.php';
const params = 'lorem=ipsum&name=binny';'POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

function transferComplete () {

http.onreadystatechange = function () {
	if (http.readyState == 4 && http.status == 200) transferComplete();