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
LLM Tool Recommendations with Better Privacy and Security
I’ve been exploring security Large Language Models (LLMs) and how to run Large Language Models (LLMs) directly on personal devices. Here are my top recommendations.
KAK Labs Newsletter #7 – Deepening My Application Security Journey
Since transitioning into the security field, I’ve specialized in Application Security. Moving forward, you can expect even more security-focused insights and analyses from my blog.
How to Defend Against Brute-Force and DoS Attacks with Fail2ban, Nginx limit_req, and iptables
In this tutorial, I’ll explain how to protect your public-facing Linux server and Nginx web server from common threats, including brute-force and DoS attacks.
Is Getting AWS Solutions Architect Associate Certification Worth It?
If you are a full-time Software Engineer, there's no strong need to pursue this certification.
DevSecOps
My Notes about DevSecOps