Search code examples
javascripthtmlajaxvariablesget

How to get multiple devices trough xhttp.open?


I have s website on my arduino, I can get 1 x the value but if i do copy the same code and alter it to the id i need to retrieve the second device it doesnt work, only 1 device at the time works... so if i delete 1 of the 2 codes it works... ANd the thing is i need to add 15 more devices trough that way, and only 1 works at the time.. what can i do now ?

I did try to use a "," or "&" no luck

This is what i did, only 1 shows up.. the code works normal as i delete 1 of them the otherone shows up...

function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("Mac").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "readMac", true);
  xhttp.send();
}


//GET LIVE SSID
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("SSID").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "readSSID", true);
  xhttp.send();
}

this is where the device shows up

<tr>
    <td><i class='fas fa-chalkboard w3-text-blue w3-large'></i></td>
    <td>MAC.</td>
    <td><span id="Mac">0</span></td>
</tr>

<tr>
    <td><i class='fas fa-chalkboard w3-text-blue w3-large'></i></td>
    <td>SSID.</td>
    <td><span id="SSID">0</span></td>
</tr>

Solution

  • If you write the same function name getData() multiple times, it will always be overwritten. So you could change the name (which would be horrible code) or (better) use the function with parameters. Something like getData(id)

    function getData(id, blubber) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById(id).innerHTML =
          this.responseText;
        }
      };
      xhttp.open("GET", blubber, true);
      // if above line is always with "read"+id you could also do
      // xhttp.open("GET", "read"+id, true); // and remove "blubber" parameter
      xhttp.send();
    }
    
    
    getData('Mac', 'readMac');
    getData('SSID', 'readSSID');