DEV Community

KAK
KAK

Posted on • Originally published at railsmine.net on

3 1

Native Javascript AJAX POST Request with Data or Parameters

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:

Neon image

Resources for building AI applications with Neon Postgres 🤖

Core concepts, starter applications, framework integrations, and deployment guides. Use these resources to build applications like RAG chatbots, semantic search engines, or custom AI tools.

Explore AI Tools →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Pieces AI Productivity Summit

​Join top AI leaders, devs, & enthusiasts for expert talks, live demos, and panels on how AI is reshaping developer productivity at the Pieces AI Productivity Summit.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️