Send POST data using XMLHttpRequest

xmlhttprequest post json
javascript send post request json
javascript post data to url
php xmlhttprequest post example
xmlhttprequest open
xmlhttprequest post response
xhr request
ajax post request

I'd like to send some data using an XMLHttpRequest in JavaScript.

Say I have the following form in HTML:

<form name="inputform" action="somewhere" method="post">
    <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">
</form>

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

The code below demonstrates on how to do this.

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('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) {
        alert(http.responseText);
    }
}
http.send(params);

XMLHttpRequest.send(), var xhr = new XMLHttpRequest(); xhr.open("POST", '/server', true); //Send the proper header information along with the request  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.

var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');

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();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send(data);

AJAX Send an XMLHttpRequest To a Server, However, always use POST requests when: A cached file is not an option (​update a file or database on the server). Sending a large amount of data to the server  The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.

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 = "http://example.com";
fetch(url, {
    method : "POST",
    body: new FormData(document.getElementById("inputform")),
    // -- or --
    // body : JSON.stringify({
        // user : document.getElementById('user').value,
        // ...
    // })
}).then(
    response => response.text() // .json(), etc.
    // same as function(response) {return response.text();}
).then(
    html => console.log(html)
);

XMLHttpRequest, Some request methods like GET do not have a body. And some of them like POST use body to send the data to the server. We'll  How to send POST request using XMLHttpRequest (XHR) #JavaScript • February 22, 2020 XMLHttpRequest (XHR) is a built-in browser object that can be used to make HTTP requests in JavaScript to exchange data between the client and server.

Minimal use of FormData to submit an AJAX request
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"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
  xhr.open (oFormElement.method, oFormElement.action, true);
  xhr.send (new FormData (oFormElement));
  return false;
}
</script>
</head>

<body>
<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"/>
</form>
</body>
</html>
Remarks
  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.

Using POST method in XMLHTTPRequest(Ajax), php"; var params = "lorem=ipsum&name=binny"; http.open("POST", url, true); //​Send the proper header information along with the request http.​setRequestHeader("  Create a XMLHTTPRequest Object that uses the POST method. See if the arguments passed to it appear in the '$_POST' array in PHP. Code XMLHTTPRequest Object. For the sake of simplicity, we are going to create the XMLHTTPRequest object using the Firefox supported ' XMLHttpRequest()' function.

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>

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

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

Ensure that your Backend API can parse JSON.

For example, in Express JS:

import bodyParser from 'body-parser'
app.use(bodyParser.json())

Send POST data in JavaScript using XMLHTTPRequest , The simplest way to send post data in JavaScript using the built-in JavaScript object XMLHTTPRequest with content type urlencoded. Since the most common use of XHR is for sending an asynchronous request with JSON payload, it's good to know how to do it. JSON stands for JavaScript Object Notation and is a popular format for sharing data with the server, and displaying the result back to the client.

How to make HTTP requests using XMLHttpRequest (XHR), To send an HTTP request using XHR, create an XMLHttpRequest The XMLHttpRequest POST request to submit a form data can be sent in  Ensure that the "POST" is pointing to the correct location. Click the Submit XMLHTTP button. When you use just the XMLHTTP object from client-side script, the same header information and data format must be observed. Step-by-Step Instruction for XMLHTTP Object. Copy the following code into a new ASP page called ClientHTTP.asp. Place the ASP page in the default Home directory.

XMLHttpRequest RESTful (GET, POST, PUT, DELETE) · GitHub, var url = "http://localhost:8080/api/v1/users";. var xhr = new XMLHttpRequest() /​post-payload-data-to-database-using-xmlhttprequest-rails?noredirect=1#. The XMLHttpRequest object is used to exchange data with a server. Send a Request To a Server To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

Using XMLHttpRequest, What are the types of send () method used for XMLHttpRequest? Questions: I'd like to send some data using an XMLHttpRequest in JavaScript. Say I have the follo

Comments
  • Is it possible to send an object in params instead of a string like in jQuery?
  • No, but @Vadorequest's comment mentioned jQuery - he asked if it were possible to pass data "like jQuery". I mentioned how I think jQuery does it and thus, how you could achieve this.
  • @EdHeal, Connection and Content-Length headers cannot be set. It'll say "Refused to set unsafe header "content-length"" . See stackoverflow.com/a/2624167/632951
  • Note: setRequestHeader() after open(). Took me an hour, let's hope this comment saves someone an hour ;)
  • is it possible to send an application/json request?
  • FormData takes the form element as its constructor argument, no need to add values indivually
  • Yes, but question was to write JavaScript equivalent of provided form not submit the form using JavaScript.
  • The answer that has few votes but got marked correct uses two extra headers: http.setRequestHeader("Content-length", params.length); and http.setRequestHeader("Connection", "close");. Are they needed? Are they perhaps only needed on certain browsers? (There is a comment on that other page saying setting the Content-Length header was "exactly what was needed")
  • @Darren Cook Implementation dependent. From my experience major browsers set 'Content-length' (it is required) automatically from the data you supply. 'Connection' header defaults to 'keep-alive' in most cases, which keeps connection open for a while so subsequent requests don't have to reestablish connection again as in case of 'close'. You can try those snippets in the console, using current page URL and inspect request headers using browser's tools or wireshark.
  • @uKolka it should be noted on the reply than with your second solution the request Content-Type changes automatically to multipart/form-data. This has serious implications on the server side and how the information is accessed there.
  • You should avoid using Promises and fat arrows for things this critical to webpage functionality, as many devices do not have browsers that support these features.
  • Promises are 90% covered. I added function() examples in case you don't prefer =>. You should absolutely be using modern JS to ease the developer experience. Worrying about a small percentage of people stuck on IE isn't worth it unless you are a huge enterprise