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

How to Send POST Data Using XMLHttpRequest in JavaScript?

DDD
Release: 2024-12-22 04:53:13
Original
948 people have browsed it

How to Send POST Data Using XMLHttpRequest in JavaScript?

Sending POST Data via XMLHttpRequest in JavaScript

In JavaScript, XMLHttpRequest provides a straightforward method for sending HTTP requests to a server, including POST requests that carry request data. Let's consider how to send data equivalent to a form using XMLHttpRequest.

Suppose you have an HTML form with the following hidden inputs:

<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 replicate this form data using XMLHttpRequest, you can utilize the following JavaScript code snippet:

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'user=person&pwd=password&organization=place&requiredkey=key';
http.open('POST', url, true);

// Send appropriate header information
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

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

In the above code, the 'params' variable contains the data to be submitted as URL-encoded key/value pairs. If you wish to create dynamic params from an object, consider the following code:

var params = new Object();
params.user = 'person';
params.pwd = 'password';
params.organization = 'place';
params.requiredkey = 'key';

// Encode the object into URL-encoded key/value pairs
let urlEncodedDataPairs = [], name;
for( name in params ) {
 urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(params[name]));
}

var params = urlEncodedDataPairs.join('&');
Copy after login

This revised 'params' variable can then be used in the XMLHttpRequest request as described earlier.

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

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template