DEV Community

loading...

Native Javascript AJAX POST Request with Data or Parameters

KAK
Creator of kaklabs.com & railsmine.net
Originally published at railsmine.net on ・1 min read

If we don’t care about response from the server, native Javascript AJAX POST request with data / parameters is quite simple.

var request = new XMLHttpRequest();
request.open('POST', '/example', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);

data variable is a body of data to be sent in the XHR request. This can be:

  • A Document, in which case it is serialized before being sent.
  • A BodyInit, which as per the Fetch spec can be a Blob, BufferSource, FormData, URLSearchParams, ReadableStream, or USVString object.

I’ve tried to send data with FormData object, but it’s not working with my Sinatra Application. So I use URLSearchParams to send the data.

Here is example of my native Javascript AJAX POST request with parameters.

var mydata = document.getElementById('mydata');
var myresponse = document.getElementById('myresponse');
var data = 'mydata=' + mydata.value;

var request = new XMLHttpRequest();
request.open('POST', 'http://example.com/mypath', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

request.onreadystatechange = function() {
  if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
    console.log('succeed');
    myresponse.value = request.responseText;
  } else {
    console.log('server error');
  }
};

request.onerror = function() {
  console.log('something went wrong');
};

request.send(data);

More Information:

Discussion (0)