Search code examples
ajaxvariablesarduinowebserveresp32

esp32 - Ajax get multiple values


I am trying to get multiple values from my ESP32 and display them on a webpage without refresh usign ajax. So far I have found only examples online that update only one vairable (see example below), but how can I update more than one variable?

code from my index.h file:

<script>
setInterval(function() {
  // Call a function repetatively with regular interval
  getData();
}, 500); //500mSeconds update rate

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

</script>

in this sample ADCValue is written with the responsetext, but what if I have multiple values coming in?


Solution

  • In esp32 server you need to response JSON message. Something like this

    {"var1": "value1", "var1": "value2"}
    

    Example code in ESP32

    // Send headers
    client.println("HTTP/1.1 200 OK");
    client.println("Content-type: application/json");
    client.println();
    
    // Send http body
    String var1 = "value1";
    String var2 = "value2";
    String jresp = "{\"var1\":\""+var1+"\",\"var1\":\""+var2+"\"}";
    client.println(jresp);
    client.println();
    

    Finally, in your JS code, you can do something like this

    xhttp.onreadystatechange = function() {
        if (http.readyState == 4) {
            try {
                var msg = JSON.parse(http.responseText);
                var var1 = msg.var1;
                var var2 = msg.var2;
                // You got 2 values above
            } catch (e) {}
        }
    }