Implementing JSON parsing in an ESP32 application using AJAX script

Currently, I am engrossed in a project that involves utilizing ESP32. I'm obtaining data from various sensors and transmitting it to a webpage hosted on the same board. After doing some research online, I learned that it's considered "better" to transmit all sensor data using the json method. Therefore, my function for retrieving and sending data looks like this:

 void handle_readings()
{
  String results_json = "{ \"data\": " + Data +
                         "," + "\"hour\": " + Hour +
                         "," + "\"ambient_temp1\": " + AmbientTemp + " }";

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

}

On testing the above function in the serial monitor, I observed the following data:

{"data": Sunday, 12/4/2020,"hour": 20:53,"ambient_temp1": 25.75}

I stumbled upon a script that can retrieve only one piece of data and display it on the page. Here is the script:

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

This is the code on my index page that displays data on the webpage:

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

<div id="page">
<h1>System XYZ</h1>

<div>
    Data: <span id="DATA">ND</span><br>
    Time: <span id="TIME">ND</span><br>
    Ambient Temperature: <span id="AMBIENTTEMP1">ND</span>
</div>

<script>
setInterval(function() {
  // Call a function repeatedly with a 1-second interval
  fetchData();
}, 1000); 

//Function to toggle an LED on my board
function sendInfo(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 fetchData() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "readings", true);
  xhttp.send();
  xhttp.onload = function() {
    if (this.status == 200) {
      var jsonResponse = JSON.parse(this.responseText);
      document.getElementById("DATA").innerHTML = jsonResponse.data;
      document.getElementById("TIME").innerHTML = jsonResponse.hour;
      document.getElementById("AMBIENTTEMP1").innerHTML = jsonResponse.ambient_temp1;
    }
    else {
      console.log(this.status);
    }
  };
}   
</script>
</div>
</body>
</html>
)=====";

The main issue I'm facing now is how to adapt this script to fetch values from multiple sensors as described in the aforementioned function. Can anybody assist me with this modification? I appreciate any help you can provide! Thank you in advance :)

Answer №1

When using the standard XMLHttpRequest, keep in mind that it only supports responseText and responseXML. This means that there isn't native support for the responseJSON property. However, if your server is sending a properly serialized JSON string, you can still access the JSON data by parsing the responseText with JSON.parse(). Once parsed, you can easily access each JSON element using 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 code snippet is compatible with all browsers that support both XMLHttpRequest and JSON, as long as the server sends a valid JSON object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty retrieving the selected value in JSPDF

I am attempting to convert my HTML page into a PDF format by utilizing the following code: domtoimage.toPng(document.getElementById('PrintForm')) .then(function (blob) { var pdf = new jsPDF('p', &apo ...

What could be causing this template to malfunction?

Every time I try to start my Express server and access the page, I encounter an error. Can anyone pinpoint what might be wrong with the syntax? The "startzeit" property is a Date() Object. <tbody> <% for (let seminar in seminare){ %> ...

Utilizing Bootstrap Modal to trigger an Action Result function when a button is clicked

I could use some assistance. In my current setup, I have a file picker that loads a file into a specific table in my database. When the user clicks a button, a bootstrap modal pops up to ask if they are uploading more files. This is how it looks in my vi ...

Python raises a TypeError with the message "List indices should be integers, not strings."

I've been struggling with this issue for the past couple of days and I just can't seem to figure it out. import urllib.request import json import base64 name = "koalaaaa" url = "https://api.mojang.com/users/profiles/minecraft/" + name rawdata = ...

Learn how to prevent two-finger swipe forward/backward on a trackpad using JavaScript or HTML

My app includes a functionality where the URL changes when transitioning from one state to another, for example from home/#state to home/#state2. However, I noticed that when I perform a two-finger swipe using the trackpad from home/#state2, the page navig ...

WooPay Multi-Currency Integration with Dynamic AJAX Technology

Currently, I have implemented WooPayments Multi-Currency to enable currency changes. It is working perfectly except when loading products through AJAX, as they continue to display in the default currency. Is there a solution to make these products appear ...

Retrieving data from a MySQL database and displaying multiple rows of information in an iOS

I have been working on a script to gather returned results, merge them into a single array, and display them in my iOS app. The desired output format is as follows: array[0]=dictionary array[1]=dictionary array[2]=dictionary However, I've encountere ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Having trouble inputting values into the Filter Value Datagrid component in Material-UI while using ReactJS

When using the Material-UI DataGrid, I'm facing an issue where I can't enter or edit any values in the filter field as shown in the image below. It appears that the filter value input is disabled. I would appreciate any assistance in resolving th ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

What is the best way to display and conceal various elements with each individual click?

Utilizing the onClick function for each triggering element, I have implemented a show/hide feature for multiple element IDs upon click. The default setting is to hide the show/hide elements using CSS display property, except for the initial 3 main elements ...

Issues with Angular radio buttons are causing them to not be selected properly

When it comes to radio buttons, they should be checked based on certain conditions. <input data-ng-checked="user.contract1 || user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes <input data-ng-checked="!user.contrac ...

Using Angular to display asynchronous data with ngIf and observables

In cases where the data is not ready, I prefer to display a loader without sending multiple requests. To achieve this, I utilize the as operator for request reuse. <div class="loading-overlay" *ngIf="this.indicatorService.loadingIndicators[this?.indic ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

The web page's content remains hidden until it is scrolled into view, despite the fact that the page has finished loading

I'm a beginner with Angular and currently working on creating a website. On the following page , when viewed on mobile, I am experiencing an issue where the content doesn't load until it's brought into view by scrolling down the page. I am u ...

Exploring your Google Map with custom markers and zoom levels extracted from an XML file

Hello, I could really use some assistance with a technical issue I am facing. I am currently working on a project that involves loading markers dynamically from an XML file using the Google Maps API and jQuery. Everything is running smoothly for the most ...

Ending a connection to MS SQL server in node.js with mssql library

In my journey to write a node.js script for querying an MSSQL database, I find myself navigating the realm of JavaScript, node.js, and VSCode with limited SQL knowledge. While I have managed to piece together working code, the issue lies in the connection ...

Empty req.body in Node.js when POST method is used

I'm completely new to exploring REST and Express, and I've been following this insightful tutorial on creating a REST API. Here's a glimpse of my programming journey through the lens of my app.js code: var express = require('express&ap ...

Tips on incorporating a fresh item into a expansive tree view using a recurring function or action - specifically geared towards the MUI React JS Tree View component

I am looking to implement a function or action that allows for the dynamic addition of new items to a tree view in MUI. The goal is to be able to click on a tree item and have it add another item, repeating this process as needed. <TreeView ...

React-Native-SVG encountered an error: Invariant Violation - the component "RNSVGGroup" could not be found in the UIManager

Trying to create an SVG in React-Native using react-native-svg. I have set up a React-Native-CLI. After doing some research, I attempted to solve the issue on my own and found something useful. I tried running cd ios && pod install. I wasn't ...