Native Javascript AJAX POST Request with Data or Parameters
- Categories:
- javascript
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:
- Tags:
- #javascript
- #ajax
- #sinatra
Recent Posts
DevSecOps
My Notes about DevSecOps
AWS Secrets Manager
Explanation about AWS Secrets Manager with example code.
Envelope Encryption
Envelope encryption is the practice of encrypting plaintext data with a data key, and then encrypting the data key under another key.
Tutorial - "su username vs su - username" - A Security Perspective
The main difference between `su username` and `su - username` lies in the environment variables that are loaded when switching to the specified user.
Subdomain Hijacking
My dormant subdomain was recently hijacked, redirecting it to a online gamble registration page.