Search code examples
javascriptjsonajaxparsingesp32

How to parse json using ajax script in ESP32 app


I am working on a project using ESP32, I get some data from some sensors and send it to a webpage hosted in the same board. I read some info on the web and understood that is "better" to send all data from several sensors using json method, so my function to get and send data is this:

 void handle_leituras()
{
  String results_json = "{ \"data\": " + Data +
                         "," + "\"hora\": " + Hora +
                         "," + "\"temp_amb1\": " + Tout + " }";

  server.send(200, "application/json", results_json);

}

Testing above function in serial monitor I have this data:

{"data": Domingo, 12/4/2020,"hora": 20:53,"temp_amb1": 25.75}

I found a script that can get only one data and print it on that page, this is the script:

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

Its my index page code that shows data on webpage:

const char pag_inicial[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My 1st test</title></head>
<html>
<body>

<div id="pagina">
<h1>System XPTO</h1>

<div>
    Data: <span id="DATA">ND</span><br>
    Hora: <span id="HORA">ND</span><br>
    Temperatura Ambiente: <span id="TEMPAMB1">ND</span>
</div>

<div id="botoes">
    <button type="button" onclick="sendData(0)" style="width: 80px; height: 30px; margin: 30px;">ON</button>
    <button type="button" onclick="sendData(1)" style="width: 80px; height: 30px; margin: 30px;">OFF</button><BR>
</div>
<script>
setInterval(function() {
  // Call a function repetatively with 1 Second interval
  getData();
}, 1000); //2000mSeconds update rate

//function to set on / off a LED on my board
function sendData(led) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("LEDState").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "setLED?LEDstate="+led, true);
  xhttp.send();
}

function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "leituras", true);
  xhttp.send();
  xhttp.onload = function() {
    if (this.status == 200) {
      var jsonResponse = JSON.parse(this.responseText);
      document.getElementById("DATA").innerHTML = jsonResponse.data;
      document.getElementById("HORA").innerHTML = jsonResponse.hora;
      document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
    }
    else {
      console.log(this.status);
    }
  };
}   
</script>
</div>
</body>
</html>
)=====";

My problem is...I don't know how to modify this script to get more sensors values from the described above function. Anybody can save me please? Thanks in advance ;)


Solution

  • The standard XMLHttpRequest only supports responseText and responseXML, it does not support responseJSON property. However, as long as your server is sending a valid serialised JSON string, the responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse(), and then you can access each JSON element with dot notation:

    function getData() {
      var xhttp = new XMLHttpRequest();
      xhttp.open("GET", "leituras", true);
      xhttp.send();
      xhttp.onload = function() {
        if (this.status == 200) {
          var jsonResponse = JSON.parse(this.responseText);
          document.getElementById("DATA").innerHTML = jsonResponse.data;
          document.getElementById("HORA").innerHTML = jsonResponse.hora;
          document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
        }
        else {
          console.log(this.status);
        }
      };
    }
    

    This piece of code works for all browsers that supports XMLHttpRequest and JSON as long as the server is sending a valid JSON object.