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

Using ASP.net MVC 4 to Implement Validation with Bootstrap Modal and PartialView

After switching from a simple View with validation to using a bootstrap modal and PartialView in my application, I encountered some issues. The client-side validation no longer works and the server-side validation redirects me to a new page instead of disp ...

Update data in PHP dynamically without reloading the page

It would be great if they are doing well! I have encountered a minor issue - everything seems to work perfectly, but it doesn't quite meet my requirements. I am referring to this particular function: <script> var previous = null; var current = ...

Activate inactive html button using javascript

One of the challenges I am facing is testing forms where the client specifically requested that the submit button be disabled by default. I have been exploring ways to dynamically replace the disabled="" attribute with enabled using JavaScript within a s ...

Leveraging Javascript within Objective-C

Can you help me understand how to implement this JavaScript code in Objective-C? var theFormId = $('form').filter(function() { return this.innerHTML.indexOf('forgot your password') != -1; }).attr('id'); Is there a way to int ...

Magento: Retrieve all new information on cart items from AJAX response

My shopping cart is displaying a popup window with the following details: I am using AJAX calls to update multiple configurable items in the cart, each with custom options simultaneously. However, I am facing an issue where I only receive data for the fi ...

Show information from table B following the selection made in table A

In my project, I need to retrieve and display data from the "foom" table once an option is selected from the "factory" table. The options in the select dropdown are populated with data from the "factory" table. The layout of the tables is as follows: Ima ...

Whenever I try to retrieve a value using the key from ModelBindingContext.ValueProvider.GetValue(key

When working with AngularJS to manipulate a complex parent object with different behaviors for its children server-side, I encountered an issue while implementing the CreateModel function as suggested in this answer. The problem arises when any call to bin ...

Syntax of the Vue.js application object model

Just delving into the world of vue.js and stumbled upon this code snippet. Curious to know more about its structure. const CounterApp = { data() { return { counter: 0 } }, mounted() { setInterval(() => { this.counter++ ...

Manipulating the DOM by linking to a div and using JSON information for opening and closing

I have retrieved data from a JSON file and displayed it as a link. I am looking to implement functionality that allows me to hide and show a div when the link is clicked. Below is the code I'm currently using: $(document).ready(function() { $ ...

``How can I effectively handle and display Angular JSON text in an alert message?

Is there a way to pass a JSON entry into the onClick event for triggering an alert box in AngularJS? I'm attempting to display a message box with the content of a specific JSON entry when clicking on a row within a table. The issue seems to be isolat ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

Creating a precise regular expression for route length in Express JS

Currently, I am facing an issue while setting a route in my application. I want the URL parameter to be exactly 2 characters long, but unfortunately, the following code snippet is not producing the desired result: app.all('/:lng{2}?',function (r ...

Place a material-ui React component at the center of a footer section

I'm facing a challenge with centering a material-ui Simple Breadcrumbs component within a footer as opposed to having it aligned to the left. Even though I'm new to this, I thought it would be straightforward but I can't seem to figure it ou ...

Revolutionary Approach to Efficiently Handle Multiple rows with Jquery

Greetings to everyone, I am currently in the process of developing an application that retrieves data from a database via AJAX by calling a .php file. Within this app, I have a table with 4 columns. The first two columns consist of dropdown menus, the thi ...

What are some strategies for stopping Knex.js from executing a query object upon return from an asynchronous function?

My node.js backend utilizes Knex.js to construct dynamic DB queries based on various inputs. The challenge I'm facing is handling asynchronous processing of certain inputs. When returning a knex query object from an async function or a Promise resolve ...

Tips for identifying the correct selectedIndex with multiple select elements present on one page

How can I maintain the correct selectedIndex of an HTMLSelectElement while having multiple select elements in a loop without any IDs? I am dynamically loading forms on a webpage, each containing a select element with a list of priorities. Each priority is ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

Unable to display bar chart on PHP webpage showing database number volumes using JavaScript

I'm currently working on generating a bar chart to show the number of bookings per month. I have two separate SQL queries that retrieve the data correctly, as confirmed by testing. However, when I try to run the file in my browser, nothing is displaye ...

JavaScript Question: How can I extract the click value from a JavaScript visualization when displayed in a table?

I am working with a Hierarchical Edge Bundling visualization in JS. My goal is to have the name of the value displayed on the table when I click on it. Currently, I am facing an issue with retrieving the value dynamically. If I manually input a value, I c ...

Saving photos from a specific tag on Instagram to a MySQL database using the Instagram API

My goal is to capture and store all images related to a specific tag on Instagram in my database. The process involves querying the API to load the initial set of images. $json = file_get_contents('https://api.instagram.com/v1/tags/hahanotfunny/medi ...