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

How Can I Send POST Data Using XMLHttpRequest in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 06:26:11601browse

How Can I Send POST Data Using XMLHttpRequest in JavaScript?

Sending POST Data with XMLHttpRequest

To transmit data via an XMLHttpRequest in JavaScript, it's essential to understand the process. 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>

To replicate this form's behavior using an XMLHttpRequest in JavaScript, follow these steps:

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);

Alternatively, if you have an object containing the data you want to send, convert it to parameters 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]));
}

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

Statement:
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