Send POST data using XMLHttpRequest

Send POST data using XMLHttpRequest

I’d like to send some data using an XMLHttpRequest in JavaScript.
Say I have the following form in HTML:

How can I write the equivalent using an XMLHttpRequest in JavaScript?


Solution 1:

The code below demonstrates on how to do this.

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';'POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {

Solution 2:

var xhr = new XMLHttpRequest();'POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // do something to response

Or if you can count on browser support you could use FormData:

var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');

var xhr = new XMLHttpRequest();'POST', 'somewhere', true);
xhr.onload = function () {
    // do something to response

Solution 3:

Use modern JavaScript!

I’d suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

const url = "";
fetch(url, {
    method : "POST",
    body: new FormData(document.getElementById("inputform")),
    // -- or --
    // body : JSON.stringify({
        // user : document.getElementById('user').value,
        // ...
    // })
    response => response.text() // .json(), etc.
    // same as function(response) {return response.text();}
    html => console.log(html)

In Node.js, you’ll need to import fetch using:

const fetch = require("node-fetch");

If you want to use it synchronously (doesn’t work in top scope):

const json = await fetch(url, optionalOptions)
  .then(response => response.json()) // .text(), etc.
  .catch((e) => {});

More Info:

Mozilla Documentation

Can I Use (92% Jun 2019)

Matt Walsh Tutorial

Solution 4:

Minimal use of FormData to submit an AJAX request

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
"use strict";
function submitForm(oFormElement)
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){ alert (xhr.responseText); } // success case
  xhr.onerror = function(){ alert (xhr.responseText); } // failure case (oFormElement.method, oFormElement.action, true);
  xhr.send (new FormData (oFormElement));
  return false;

<form method="post" action="somewhere" onsubmit="return submitForm(this);">
  <input type="hidden" value="person"   name="user" />
  <input type="hidden" value="password" name="pwd" />
  <input type="hidden" value="place"    name="organization" />
  <input type="hidden" value="key"      name="requiredkey" />
  <input type="submit" value="post request"/>


  1. This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.

  2. This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.

  3. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.

Solution 5:


Just drag any link (i.e. THIS LINK) in BOOKMARK BAR (if you dont see it, enable from Browser Settings), then EDIT that link :

enter image description here

and insert javascript code:

javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); };, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);

That’s all! Now you can visit any website, and click that button in BOOKMARK BAR!


The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script. That’s why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain – here is code for that:

 javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) {   var xForm= document.createElement("form");   xForm.setAttribute("method", "post");   xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank");   for(var key in params) {   if(params.hasOwnProperty(key)) {        var hiddenField = document.createElement("input");      hiddenField.setAttribute("name", key);      hiddenField.setAttribute("value", params[key]);         xForm.appendChild(hiddenField);     }   }   document.body.appendChild(xForm);  xForm.submit(); }   parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0); 

Solution 6:

Here is a complete solution with application-json:

// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">

// return stops normal action and runs login()
<button onclick="return login()">Submit</button>

    function login() {
        // Form fields, see IDs above
        const params = {
            email: document.querySelector('#loginEmail').value,
            password: document.querySelector('#loginPassword').value

        const http = new XMLHttpRequest()'POST', '/login')
        http.setRequestHeader('Content-type', 'application/json')
        http.send(JSON.stringify(params)) // Make sure to stringify
        http.onload = function() {
            // Do whatever with response

Ensure that your Backend API can parse JSON.

For example, in Express JS:

import bodyParser from 'body-parser'