0

I am trying to read json encoded page, get value from it and make it into graph on a page.

This is how the json document looks like:

[{"time":"1561430809","ip":"192.168.102.166","waterlevel":null,"station":null,"humidity":null,"temperature":null},{"time":"1561390045","ip":"192.168.103.151","waterlevel":"419","station":"Near the Training Center","humidity":"0","temperature":"0"}]

And here is theg page code:

<!doctype html>
<html>
 
<head>
  <title>Line Chart | Abaarso school</title>
  <!--For offline ESP graphs see this tutorial https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ -->
  <script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>  
  <style>
  canvas{
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
  }
 
  /* Data Table Styling */
  #dataTable {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
  }
 
  #dataTable td, #dataTable th {
    border: 1px solid #ddd;
    padding: 8px;
  }
 
  #dataTable tr:nth-child(even){background-color: #f2f2f2;}
 
  #dataTable tr:hover {background-color: #ddd;}
 
  #dataTable th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #4CAF50;
    color: white;
  }
  </style>
</head>
 
<body>
    <div style="text-align:center;"><b>test</b><br></br>Real Time Data: Humidity, Temperature Logging with Graphs</div>
    <div class="chart-container" position: relative; height:350px; width:100%">
        <canvas id="Chart" width="400" height="400"></canvas>
    </div>
<div>
  <table id="dataTable">
    <tr><th>Time</th><th>Water level (ml)</th><th>Temperaure (&deg;C)</th><th>Humidity (%)</th></tr>
  </table>
</div>
<br>
<br>  
 
<script>
//Graphs visit: https://www.chartjs.org
var ADCvalues = [];
var Tvalues = [];
var Hvalues = [];
var timeStamp = [];
function showGraph()
{
    var ctx = document.getElementById("Chart").getContext('2d');
    var Chart2 = new Chart(ctx, {
        type: 'line',
        data: {
            labels: timeStamp,  //Bottom Labeling
            datasets: [{
                label: "water level",
                fill: false,  //Try with true
                backgroundColor: 'rgba( 243,18, 156 , 1)', //Dot marker color
                borderColor: 'rgba( 243, 18, 156 , 1)', //Graph Line Color
                data: ADCvalues,
            },{
                label: "Temperature",
                fill: false,  //Try with true
                backgroundColor: 'rgba( 243, 156, 18 , 1)', //Dot marker color
                borderColor: 'rgba( 243, 156, 18 , 1)', //Graph Line Color
                data: Tvalues,
            },
            {
                label: "Humidity",
                fill: false,  //Try with true
                backgroundColor: 'rgba(156, 18, 243 , 1)', //Dot marker color
                borderColor: 'rgba(156, 18, 243 , 1)', //Graph Line Color
                data: Hvalues,
            }],
        },
        options: {
            title: {
                    display: true,
                    text: "Station A: near the training center"
                },
            maintainAspectRatio: false,
            elements: {
            line: {
                    tension: 0.5 //Smoothening (Curved) of data lines
                }
            },
            scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
            }
        }
    });
 
}
 
//On Page load show graphs
window.onload = function() {
  console.log(new Date().toLocaleTimeString());
};
 
//Ajax script to get ADC voltage at every 5 Seconds 
//Read This tutorial https://circuits4you.com/2018/02/04/esp8266-ajax-update-part-of-web-page-without-refreshing/
 
setInterval(function() {
  // Call a function repetatively with 5 Second interval
  getData();
}, 5000); //5000mSeconds update rate
 
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     //Push the data in array
  var time = new Date().toLocaleTimeString();
  var txt = this.responseText;
  var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
      ADCvalues.push(obj.waterlevel);
      Tvalues.push(obj.temperature);
      Hvalues.push(obj.humidity);
      timeStamp.push(time);
      showGraph();  //Update Graphs
  //Update Data Table
    var table = document.getElementById("dataTable");
    var row = table.insertRow(1); //Add after headings
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    cell1.innerHTML = time;
    cell2.innerHTML = obj.waterlevel;
    cell3.innerHTML = obj.temperature;
    cell4.innerHTML = obj.humidity;
    }
  };
  xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); //Handle readADC server on ESP8266
  xhttp.send();
}
    
</script>
</body>
 
</html>
 

I don't get the values from my local json page and thus can't graph it. What am I getting wrong here? I just need to get the values from the json encoded page and then show them on a line graph.

This is the error.

Uncaught TypeError: Cannot read property 'skip' of undefined
    at l (Chart.min.js:10)
    at u (Chart.min.js:10)
    at a (Chart.min.js:10)
    at t.getElementsAtEventForMode (Chart.min.js:10)
    at t.handleEvent (Chart.min.js:10)
    at t.eventHandler (Chart.min.js:10)
    at n (Chart.min.js:10)
    at HTMLCanvasElement.x.<computed> (Chart.min.js:10)
133Chart.min.js:10 Uncaught TypeError: Cannot read property 'skip' of undefined
    at l (Chart.min.js:10)
    at u (Chart.min.js:10)
    at a (Chart.min.js:10)
    at t.getElementsAtEventForMode (Chart.min.js:10)
    at t.handleEvent (Chart.min.js:10)
    at t.eventHandler (Chart.min.js:10)
    at n (Chart.min.js:10)
    at HTMLCanvasElement.x.<computed> (Chart.min.js:10)

The code in the Json.php is:

<?php
$dab=new PDO('sqlite:waterlevel');
$st=$dab->prepare('select time, ip, waterlevel, station, humidity, temperature from waterlevel group by station order by time desc limit 100');
$st->execute();
$sv=$st->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($sv);
?>
Monolica
  • 115
  • 7
  • Have you try to debug it? What's the error message that you get? – Andra Jun 25 '19 at 03:04
  • once i try to print values, i just get null for return – Monolica Jun 25 '19 at 03:09
  • Does the table shows you undefined value?. Try to right click on your page and open the console section, there's should be the error message. – Andra Jun 25 '19 at 03:18
  • Also, may I see the `json.php` ? Why the json file has a null value for the first array element? – Andra Jun 25 '19 at 03:22
  • All codes are added to the top. please see. – Monolica Jun 25 '19 at 03:26
  • There's `order by time desc limit 100` on `json.php`, so you mean you want to get a 100 row data every 5 second? I have to make it sure, because your first array element contains null value, or it might because your database has a null value on one of it's row – Andra Jun 25 '19 at 03:30

1 Answers1

1

The error appears because you are trying to accessing array of object values, you have a multiple object, not just one, so you might want to iterate them. One of the solution to iterate throught it are by using forEach() (read here).

You also might have to chage your database columns to be not nullable.

<!DOCTYPE html>
<html>
    <head>
        <title>Line Chart | Abaarso school</title>
        <!--For offline ESP graphs see this tutorial https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ -->
        <script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
        <meta charset="UTF-8">
        <style>
        canvas{
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
        }

        /* Data Table Styling */
        #dataTable {
            font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        #dataTable td, #dataTable th {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #dataTable tr:nth-child(even){background-color: #f2f2f2;}

        #dataTable tr:hover {background-color: #ddd;}

        #dataTable th {
            padding-top: 12px;
            padding-bottom: 12px;
            text-align: left;
            background-color: #4CAF50;
            color: white;
        }
        </style>
    </head>
    <body>
        <div style="text-align:center;"><b>test</b><br></br>Real Time Data: Humidity, Temperature Logging with Graphs</div>
        <div class="chart-container" position: relative; height:350px; width:100%">
            <canvas id="Chart" width="400" height="400"></canvas>
        </div>
        <div>
            <table id="dataTable">
                <tr><th>Time</th><th>Water level (ml)</th><th>Temperaure (&deg;C)</th><th>Humidity (%)</th></tr>
            </table>
        </div>
        <br>
        <br>  

        <script>
        //Graphs visit: https://www.chartjs.org
        var ADCvalues = [];
        var Tvalues = [];
        var Hvalues = [];
        var timeStamp = [];
        function showGraph()
        {
            var ctx = document.getElementById("Chart").getContext('2d');
            var Chart2 = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: timeStamp,  //Bottom Labeling
                    datasets: [{
                        label: "water level",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba( 243,18, 156 , 1)', //Dot marker color
                        borderColor: 'rgba( 243, 18, 156 , 1)', //Graph Line Color
                        data: ADCvalues,
                    },{
                        label: "Temperature",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba( 243, 156, 18 , 1)', //Dot marker color
                        borderColor: 'rgba( 243, 156, 18 , 1)', //Graph Line Color
                        data: Tvalues,
                    },
                    {
                        label: "Humidity",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba(156, 18, 243 , 1)', //Dot marker color
                        borderColor: 'rgba(156, 18, 243 , 1)', //Graph Line Color
                        data: Hvalues,
                    }],
                },
                options: {
                    title: {
                            display: true,
                            text: "Station A: near the training center"
                        },
                    maintainAspectRatio: false,
                    elements: {
                    line: {
                            tension: 0.5 //Smoothening (Curved) of data lines
                        }
                    },
                    scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero:true
                                }
                            }]
                    }
                }
            });

        }

        //On Page load show graphs
        window.onload = function() {
          console.log(new Date().toLocaleTimeString());
        };

        //Ajax script to get ADC voltage at every 5 Seconds 
        //Read This tutorial https://circuits4you.com/2018/02/04/esp8266-ajax-update-part-of-web-page-without-refreshing/

        setInterval(function() {
          // Call a function repetatively with 5 Second interval
          getData();
        }, 5000); //5000mSeconds update rate

        function getData() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    //Push the data in array
                    var time = new Date().toLocaleTimeString();
                    var txt = this.responseText;
                    var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
                    console.log(obj);
                    obj.forEach(function(element_data){
                        console.log(element_data);
                        ADCvalues.push(element_data.waterlevel);
                        Tvalues.push(element_data.temperature);
                        Hvalues.push(element_data.humidity);
                        timeStamp.push(time);
                        showGraph();
                        var table = document.getElementById("dataTable");
                        var row = table.insertRow(1); //Add after headings
                        var cell1 = row.insertCell(0);
                        var cell2 = row.insertCell(1);
                        var cell3 = row.insertCell(2);
                        var cell4 = row.insertCell(3);
                        cell1.innerHTML = time;
                        cell2.innerHTML = element_data.waterlevel;
                        cell3.innerHTML = element_data.temperature;
                        cell4.innerHTML = element_data.humidity;
                    });
                }
            };
            xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); // Works fine with me using the same json document locally - Handle readADC server on ESP8266
            xhttp.send();
        }
        </script>
    </body>
</html>
Andra
  • 1,282
  • 2
  • 11
  • 34
  • I changed the database columns to be not nullable and not it works find. But still, no values are received. here is the console error: 4abdikani.local.ask.org/json.php:1 Failed to load resource: net::ERR_NAME_NOT_RESOLVED 4graphs.html:153 GET http://abdikani.local.ask.org/json.php net::ERR_NAME_NOT_RESOLVED – Monolica Jun 25 '19 at 09:51
  • Well, I can't also open http://abdikani.local.ask.org/json.php . Are you sure that's the whole error output? Try to download the json, save it to your machine and change the `xhttp.open()` url to it. If it's work, then the problem is not in the code, but the website itself. – Andra Jun 25 '19 at 15:22
  • The website is running on local nginx server, with php installed. – Monolica Jun 25 '19 at 16:06