Home » NodeMCU » NodeMCU Ajax: Dynamic Sensor Data on Web Page
nodemcu ajax dynamic sensor data

NodeMCU Ajax: Dynamic Sensor Data on Web Page

Last time we managed to display sensor data to a NodeMCU web server. The problem with that code is that we need to refresh the page manually in order to update the sensor value. A better method is to use ajax (asynchronous javascript and xml) so that we can request data from the server in the background with no page reloads.

Ajax is a combination of an XMLHttpRequest object and javascript. The XMLHttpRequest object performs the request on the server while the javascript DOM object updates the element on the web page. Besides updating page elements without reload, ajax also makes it possible to a) request data from a server - after the page has loaded; b) receive data from a server - after the page has loaded and c) send data to a server - in the background. W3Schools has a great tutorial on ajax.

We shall now edit the sketch from last time to include ajax script. We will be using the same schematic:

nodemcu ajax sensor

Here is the ajax script that we’ll be using:

The main ajax script is the loadData() function. Inside this function, an XMLHttpRequest() object is created. The server waits for a readystate of 4 (done) and a http status of 200 (OK) before the web page element is updated via callback to updateData(). The request is then initiated via the open() and send() functions. Callback was necessary here to make the requests asynchronous, i.e., make the page still responsive even if there is a pending request.

In order for this function to be repeatedly called, we will be using the javascript setInterval() function. Here the loadData() function is called every second.

There are a couple of ways to get data from the sensor. What I did was save the data to a text file. This text file will then be read by the XMLHttpRequest object and then display its contents to the page element.

Full Code

 

Video:


 

You can also add CSS to make the web page look nicer. If you want to record the sensor readings, you can send NodeMCU data to Google sheets or save it to a database.

Check Also

Adding Location to Microcontroller Projects: GPS Tutorial

Global Positioning System (GPS) has been around since the 80's and is still one of …

Leave a Reply

Your email address will not be published. Required fields are marked *