Home > Web Front-end > JS Tutorial > How Can I Use XMLHttpRequest to Send POST Data in JavaScript?

How Can I Use XMLHttpRequest to Send POST Data in JavaScript?

Barbara Streisand
Release: 2024-12-19 05:43:08
Original
113 people have browsed it

How Can I Use XMLHttpRequest to Send POST Data in JavaScript?

POST Data Transmission Using XMLHttpRequest

In JavaScript, the XMLHttpRequest object provides a way to send data to a server asynchronously. This can be useful when transmitting form data without reloading the page.

Converting a Form Submission to XMLHttpRequest

Consider the following HTML form:

<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>
Copy after login

To achieve the equivalent functionality using XMLHttpRequest, we can write the following code:

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);
Copy after login

This code opens a POST request to the specified URL, sets the necessary header information, and sends the parameters. You can modify the 'params' variable to include any data you need to transmit.

Object-to-Parameter Conversion

If you have an object you want to send as parameters, you can convert it to an array of URL-encoded key/value pairs using the following code:

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

let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
    urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}
Copy after login

This will create a string that can be used as the request parameters in the 'params' variable in the XMLHttpRequest call.

The above is the detailed content of How Can I Use XMLHttpRequest to Send POST Data in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template