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?
send() 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.
To send data using the HTTP POST method, you must include the data in the body of the HTTP POST message and specify the MIME type of the data with a Content-Type header. Below is an example of an HTTP POST request to send JSON data to the server. The size and data type for HTTP POST requests is not limited.
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])); }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With