Search code examples
javascriptwebformsxmlhttprequest

Passing multiple parameters by POST using XMLHttpRequest and HTML


I'm trying to pass multiple parameters via HTML form into a XMLHttpRequest. The request takes a network SSID and PSK and passes it to the /connect endpoint.

It works when I hardcode the SSID and PSK using:

var data = '{"ssid":"homenetwork", "psk":"mypassword"}';
xhr.send(data);

When I try to pull the data from the HTML form I get net::ERR_EMPTY_RESPONSE in Chrome.

<!DOCTYPE html>
<html>
<br>

<label for="network">Network Name (SSID):</label>
<input type="text" id="network" name="network" required size="15">

<label for="presharedkey">Network Password (PSK): </label>
<input type="text" id="presharedkey" name="presharedkey" required size="15">


<button onclick="connectWifi()">Save</button> <br>

<script>
function connectWifi() {
var network = document.getElementById("network") .value;
var presharedkey = document.getElementById("presharedkey") .value;
var url = "http://192.168.0.236:8080/connect";
var xhr = new XMLHttpRequest();

xhr.open("POST", url);

xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

   // var data = '{"ssid":"homenetwork", "psk":"mypassword"}';
   var data = 'ssid='+network+'&psk='+presharedkey;
   xhr.send(data);

}
</script>

</html>

The var data = line I pulled from this StackOverflow question.

Thanks in advance.


Solution

  • The data variable you are using needs to be a JSON object. In your example here it is a string, so the individual values are not passed, just one single string.

    Try:

    var data = `{"ssid": "${network}", "psk": "${presharedkey}"}`;

    [EDIT] I misunderstood the original question it seems. OP is trying to send the data as a JSON object but doesn't know how to format it (they claim manually passing the string of variables works).