Skip to content
Fix Code Error

Send POST data using XMLHttpRequest

March 13, 2021 by Code Error
Posted By: Anonymous

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?

Solution

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);

In case you have/create an object you can turn it into params using the following code, i.e:

var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;

// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
 urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}
Answered By: Anonymous

Related Articles

  • How to properly do JSON API GET requests and assign output…
  • How to parse JSON with XE2 dbxJSON
  • The 'compilation' argument must be an instance of…
  • Azure Availability Zone ARM Config
  • Avoid creating new session on each axios request laravel
  • Event Snippet for Google only shows one event while testing…
  • Search match multiple values in single field in…
  • NullpointerException error while working with choiceBox and…
  • loop and eliminate unwanted lines with beautiful soup
  • Why does this Azure Resource Manager Template fail…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Center image using text-align center?

Next Post:

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error