Variables into HTML table not working


#1

[Continuing from: Reading Spark Variables with Your Own HTML File]

Hello BKO,

I have adopted your code to display my data into my HTML table, it doesn’t seem to be working for me, I have 5 particle devices and I would like to display the 5 devices data to be published like the events in console.particle.io Here is my HTML code.

    <div class="container">
        <div class="tab tab-1">

            <table id="table" border="1">
                <tr>
                    <th>eTrap List</th>
                    <th>Location</th>
                    <th>Start Date</th>
                    <th>End Date</th>
                    <th>Motion Detected</th>
                    <th>Battery Level</th>

                </tr>

            </table>

        </div>
        <div class="tab tab-2">

          Select eTrap:<br>
          <select id= "trap" name="eTraps">
            <option value="eTrap 1">eTrap 1</option>
            <option value="eTrap 2">eTrap 2</option>
            <option value="eTrap 3">eTrap 3</option>
            <option value="eTrap 4">eTrap 4</option>
           
          </select><br><br>

            location:<br>
            <input type="text" id= "local" name="location" value="Melbourne">
            <br>
          </form>

           Start date:<br>
          <input type="date" id="myDate" value="2017-12-09"><br><br>


          End date:<br>
         <input type="date" id="myDateEnd" value="2014-02-09"><br>


            <button onclick="addHtmlTableRow();">Add</button>
            <button onclick="editHtmlTbleSelectedRow();">Edit</button>
            <button onclick="removeSelectedRow();">Remove</button>
            <button onclick="getliveupdate();">Live status</button>
        </div>
    </div>

    <script>

        var rIndex,
            table = document.getElementById("table");

        // check the empty input
        function checkEmptyInput()
        {
            var isEmpty = false,
                trap = document.getElementById("trap").value,
                local = document.getElementById("local").value,
                myDate = document.getElementById("myDate").value,
                myDateEnd = document.getElementById("myDateEnd").value;

            if(local === ""){
                alert("Location Connot Be Empty");
                isEmpty = true;
            }
            else if(myDate === ""){
                alert("Start Date Connot Be Empty");
                isEmpty = true;
            }
            else if(myDateEnd === ""){
                alert("End Date Connot Be Empty");
                isEmpty = true;
            }
            return isEmpty;
        }

        // add Row
        function addHtmlTableRow()
        {
            // get the table by id
            // create a new row and cells
            // get value from input text
            // set the values into row cell's
            if(!checkEmptyInput()){
            var newRow = table.insertRow(table.length),
                cell1 = newRow.insertCell(0),
                cell2 = newRow.insertCell(1),
                cell3 = newRow.insertCell(2),
                cell4= newRow.insertCell(3),
                cell5 =newRow.insertCell(4),
                cell6= newRow.insertCell(5),

                trap = document.getElementById("trap").value,
                local = document.getElementById("local").value,
                myDate = document.getElementById("myDate").value,
                myDateEnd = document.getElementById("myDateEnd").value;

            cell1.innerHTML = trap;
            cell2.innerHTML = local;
            cell3.innerHTML = myDate;
            cell4.innerHTML = myDateEnd;
            // call the function to set the event to the new row
            selectedRowToInput();
        }
        }

        // display selected row data into input text
        function selectedRowToInput()
        {

            for(var i = 1; i < table.rows.length; i++)
            {
                table.rows[i].onclick = function()
                {
                  // get the seected row index
                  rIndex = this.rowIndex;
                  document.getElementById("trap").value = this.cells[0].innerHTML;
                  document.getElementById("local").value = this.cells[1].innerHTML;
                  document.getElementById("myDate").value = this.cells[2].innerHTML;
                  document.getElementById("myDateEnd").value = this.cells[3].innerHTML;
                };
            }
        }
        selectedRowToInput();

        function editHtmlTbleSelectedRow()
        {
            var trap = document.getElementById("trap").value,
                local = document.getElementById("local").value,
                myDate = document.getElementById("myDate").value,
                myDateEnd = document.getElementById("myDateEnd").value;
           if(!checkEmptyInput()){
            table.rows[rIndex].cells[0].innerHTML = trap;
            table.rows[rIndex].cells[1].innerHTML = local;
            table.rows[rIndex].cells[2].innerHTML = myDate;
            table.rows[rIndex].cells[3].innerHTML = myDateEnd;
          }
        }

        function removeSelectedRow()
        {
            table.deleteRow(rIndex);
            // clear input text
            document.getElementById("trap").value = "";
            document.getElementById("local").value = "";
            document.getElementById("myDate").value = "";
            document.getElementById("myDateEnd").value = "";
        }

    </script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8">
    <span id="battery">Waiting for data...</span><br>
        <span id="tstamp"></span><br>
        function getlivestatus(){
          for(var i = 1; i < table.rows.length; i++)
          {
              table.rows[i].onclick = function()
              {
          if (cell1.innerHTML == "eTrap 1"){
           window.setInterval(function() {

            var deviceID = "570040001951353338363036";
            var accessToken = "fd4b398a359ad4c81c3589bb3d90ad5c3959bd91";
            var varName = "battery";
            requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + varName + "/?access_token=" + accessToken;
            $.getJSON(requestURL, function(json) {
              document.getElementById("battery").innerHTML = json.result;
              cell5.innerHTML= document.getElementById("battery").innerHTML;
                     });

        },5000);
      }
    }}
  }
    </script>

</body>

Kindly please help me to pass my variable into the particular cell in the HTML page

Thanks,
Gowtham


Reading Spark Variables with Your Own HTML File
Reading Spark Variables with Your Own HTML File
Reading Spark Variables with Your Own HTML File
#2

If only you mentioned what didn’t work, what it is doing instead, and what you’ve tried to fix that, that would’ve been great.

Meanwhile, you say you want to display publishes like the console, yet are using variables.

Furthermore, you mention to be using 5 device, only one of which can be seen in your code.

I think we need some more information to be able to assist properly.


#3

Hello Moors7,

my dashboard looks like this, I can add, edit and delete the rows. Eventually, I need to display the data from the particle electron on the two columns with respect to the device selected. for instance, if select etrap 1, data respect to the device should display in the motion detected and battery level column. I tried with selecting 1 device , but its showing nothing in the motion detected column and battery column. Kindly help me where I was wrong in the coding.


#4

Hmm, as @moors7 already stated, you only got one device ID defined in your code and are also only requestion one variable (i.e. battery). So no wonder you don’t get any motion info.

Also instead of just showing the screen shot, providing your firmware code may have been more important.
Which device is the one you got the device ID hardcoded for?
What happens when you select that particlular one?
Are your devices permanently online?


#5

Seeing as the code you’ve posted is incomplete, there’s no way for us to test it (other than finishing/fixing the code first, which I’m personally not interested in).

Looking at the code you’ve got, there seem to be some high level mistakes, such as creating the battery <span> inside the <script> tags. Pretty sure that’s not going to work.

Might I suggest you first try the example by @bko, and try it with one device only. Then, once that works, slowly, and step by step, work towards the end goal. That often works better than trying to do everything at once, and then figuring out something isn’t working.


#6

@Moors7 I have tried his @bko code separately and I got results.But it isn’t working when I try to push the same data to the table. yes, I understand that inside the that was just an editing error. Hence i corrected the mistake. But I am confused where it went wrong.

Thanks,
Gowtham


#7

@ScruffR I am just testing with one device to verify the code. But I am not getting anything. My particle device is connected to the motion sensor. When there is an interruption, the device will wake up and publish the data. @bko’ s code works perfectly, it isn’t working for me when trying to post data to the table.


#8

And there’s the issue… If your device is asleep, the webpage can’t request the variable data, and as such can’t update the table with anything useful. For Variables to work, your device needs to be online when you request them. @ScruffR alluded to this as well:

That’s why this little bit is quite important:


#9

@Moors7 @ScruffR
this is my source code

#include "application.h"
SYSTEM_MODE(AUTOMATIC);
STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY));
SYSTEM_THREAD(ENABLED);
char publishString[63];
uint32_t lastTime;
bool receivedflag;
double value;
float percentage;
float alert;
//double _now;
//double _sleep_sec;
//int lowbat=3.3;
//int highbat=3.7;

int led = D7; // we will use D7 LED to monitor sensor activity

void doConnect() {
    Cellular.on();
     if (!Cellular.ready()) {
        Cellular.connect();
    while(Cellular.connecting())
    {
         Particle.process(); //SPARK_WLAN_Loop();
        delay(1000);
       }//while(cellular.connecting())
    }//if (!cellular.ready())

    if(!Particle.connected()){
    Particle.connect();
    while(!Particle.connected()){
        Particle.process(); //SPARK_WLAN_Loop();
        delay(1000);
        }//while(!Spark.connected())
    }//if(!Spark.connected())       
}//doConnect

void myHandler(const char *event, const char *data){
    receivedflag = TRUE;
}//myhandler

void setup() {
    doConnect();
    Time.zone(+11);
    Particle.variable("battery", value);
    Particle.subscribe("ReceivedMotionTime", myHandler, MY_DEVICES); 
    lastTime = millis();
    while(millis() - lastTime < 3000) {
        Particle.process();
       
    }
    receivedflag = FALSE;   
    FuelGauge fuel;
    value = fuel.getVCell();
    percentage =fuel.getSoC();
 
 //_now = Time.now();
 
// _sleep_sec = _now + 18.5 ;

}//setup

void loop(){
FuelGauge fuel;

    Particle.disconnect();
    Cellular.disconnect();
    Cellular.off(); 
    System.sleep(WKP,RISING, _sleep_sec,SLEEP_NETWORK_STANDBY ); //,30); //Sleep indefinitely till A7 HIGH    
    doConnect();
    if (Particle.connected()) {     
       // String output = "{\"batt-value\": \"" + String(value) + "\"}";
        
        if (fuel.getSoC() >= 50)
        {
            
        Particle.publish("fuel-level1", String(percentage)); 
        Particle.publish("fuel-level2", String(value));
        lastTime = millis();
        sprintf(publishString,"%04d/%02d/%02d %02d:%02d:%02d",Time.year(),Time.month(),
        Time.day(),Time.hour(),Time.minute(),Time.second(), percentage);
       
        Particle.publish("EVENT_SMART_TRAP",publishString, 60);
           lastTime = millis();
        while( (!receivedflag)  && (millis() - lastTime < 10000) ) { // 10s allows catching receipt msg
            Particle.process();
            if (receivedflag == TRUE) { //confirm receipt msg          
               digitalWrite(D7, HIGH);
                lastTime = millis();
                while(millis() - lastTime < 200) {Particle.process();}        
                digitalWrite(D7, LOW);     
           }//if (receivedflag == TRUE)
         }//while((!receivedflag) && (millis() - lastTime < SOFTDELAY3s)) 
    }//if (Spark.connected())
    }
    else{
        
        Particle.publish("lowbattery", String(percentage));
    }
    
     
    receivedflag = FALSE;   
}//loop

#10

System.sleep(WKP,RISING, _sleep_sec,SLEEP_NETWORK_STANDBY );
That will reset the device, so that any statements after that will never run. That also means your device goes to sleep as soon as it reaches the loop. Thus, variables will be unavailable.
That’s documented behavior though…


#11

This function, which is the way things are updated by refreshing the page, does not have access to other function’s variables cell1 and cell5. The only globally accessible data structure you can get to is your table (called “table”) so you have to do something like this:

  var dt = document.getElementById("table");
  var rowN = dt.rows[1];
  var cell1 = rowN.cells[0];
  var cell5 = rowN.cells[4];

If you need to handle multiple rows in the table, then you need to either “know” that row 1 is eTrap 1 etc. or search the table for the string “eTrap 1” in cell[0].


#12

@Moors7 please see screenshot.

I am getting results if I use the HTML code in the separate page , but i am not able to push the data into the table.

Thanks,
Gowtham


#14

I haven’t tried, but given …

… I’d guess this is not the code you are running, as it wouldn’t build for an undefined variable _sleep_sec.


#15

Hello @bko ,

Please find the below code

<!DOCTYPE html>
<html>
    <head>
        <title>eTrap</title>
        <meta charset="windows-1252">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <style>

            .container{overflow: hidden}
            .tab{float: left;}
            .tab-2{margin-left: 50px}
            .tab-2 input{display: block;margin-bottom: 10px}
            tr{transition:all .25s ease-in-out}
            tr:hover{background-color:#EEE;cursor: pointer}

        </style>

    </head>
    <body>

        <div class="container">
            <div class="tab tab-1">

                <table id="table" border="1">
                    <tr>
                        <th>eTrap List</th>
                        <th>Location</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Core ID</th>
                        <th>Rodent Detected</th>
                        <th>Battery Level</th>

                    </tr>

                </table>

            </div>
            <div class="tab tab-2">

              Select eTrap:<br>
              <select id= "trap" name="eTraps">
                <option value="eTrap 1">eTrap 1</option>
                <option value="eTrap 2">eTrap 2</option>
                <option value="eTrap 3">eTrap 3</option>
                <option value="eTrap 4">eTrap 4</option>
                <option value="eTrap 5">eTrap 5</option>
               
              </select><br><br>

                location:<br>
                <input type="text" id= "local" name="location" value="Melbourne">
                <br>
              </form>

               Start date:<br>
              <input type="date" id="myDate" value="2017-12-09"><br><br>


              End date:<br>
             <input type="date" id="myDateEnd" value="2014-02-09"><br>


                <button onclick="addHtmlTableRow();">Add</button>
                <button onclick="editHtmlTbleSelectedRow();">Edit</button>
                <button onclick="removeSelectedRow();">Remove</button>
                <button id ="connectbutton" onclick="getliveupdate();">Live status</button>
            </div>
        </div>

        <script>

            var rIndex,
                table = document.getElementById("table");

            // check the empty input
            function checkEmptyInput()
            {
                var isEmpty = false,
                    trap = document.getElementById("trap").value,
                    local = document.getElementById("local").value,
                    myDate = document.getElementById("myDate").value,
                    myDateEnd = document.getElementById("myDateEnd").value;


                if(local === ""){
                    alert("Location Connot Be Empty");
                    isEmpty = true;
                }
                else if(myDate === ""){
                    alert("Start Date Connot Be Empty");
                    isEmpty = true;
                }
                else if(myDateEnd === ""){
                    alert("End Date Connot Be Empty");
                    isEmpty = true;
                }
                return isEmpty;
            }

            // add Row
            function addHtmlTableRow()
            {
                // get the table by id
                // create a new row and cells
                // get value from input text
                // set the values into row cell's
                if(!checkEmptyInput()){
                var newRow = table.insertRow(table.length),
                    cell1 = newRow.insertCell(0),
                    cell2 = newRow.insertCell(1),
                    cell3 = newRow.insertCell(2),
                    cell4= newRow.insertCell(3),
                    cell5 =newRow.insertCell(4),
                    cell6= newRow.insertCell(5),
                    cell7=newRow.insertCell(6),

                    trap = document.getElementById("trap").value,
                    local = document.getElementById("local").value,
                    myDate = document.getElementById("myDate").value,
                    myDateEnd = document.getElementById("myDateEnd").value;



                cell1.innerHTML = trap;
                cell2.innerHTML = local;
                cell3.innerHTML = myDate;
                cell4.innerHTML = myDateEnd;

                //cell5.innerHTML = parsedData.coreid;
                //cell6.innerHTML = parsedData.data;
                //cell7.innerHTML = parsedData.published_at;
                // call the function to set the event to the new row
                selectedRowToInput();
            }
            }

            // display selected row data into input text
            function selectedRowToInput()
            {

                for(var i = 1; i < table.rows.length; i++)
                {
                    table.rows[i].onclick = function()
                    {
                      // get the seected row index
                      rIndex = this.rowIndex;
                      document.getElementById("trap").value = this.cells[0].innerHTML;
                      document.getElementById("local").value = this.cells[1].innerHTML;
                      document.getElementById("myDate").value = this.cells[2].innerHTML;
                      document.getElementById("myDateEnd").value = this.cells[3].innerHTML;
                    };
                }
            }
            selectedRowToInput();

            function editHtmlTbleSelectedRow()
            {
                var trap = document.getElementById("trap").value,
                    local = document.getElementById("local").value,
                    myDate = document.getElementById("myDate").value,
                    myDateEnd = document.getElementById("myDateEnd").value;
               if(!checkEmptyInput()){
                table.rows[rIndex].cells[0].innerHTML = trap;
                table.rows[rIndex].cells[1].innerHTML = local;
                table.rows[rIndex].cells[2].innerHTML = myDate;
                table.rows[rIndex].cells[3].innerHTML = myDateEnd;
              }
            }

            function removeSelectedRow()
            {
                table.deleteRow(rIndex);
                // clear input text
                document.getElementById("trap").value = "";
                document.getElementById("local").value = "";
                document.getElementById("myDate").value = "";
                document.getElementById("myDateEnd").value = "";
            }
            function getliveupdate(objButton)
            {
              document.getElementById("connectbutton").innerHTML = "Running";
              window.setInterval( function () {

                  var eventName = "fuel-level1";
                  var deviceID = "36003a001951353338363036";
                  var accessToken = "5f86bc3893f296a64aab717107e10a18f0dda661";

              var requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/events/?access_token=" + accessToken;

                  var eventSource = new EventSource(requestURL);

                  eventSource.addEventListener('open', function(e) {
                      console.log("Opened!"); },false);

                  eventSource.addEventListener('error', function(e) {
                      console.log("Errored!"); },false);

                  eventSource.addEventListener(eventName, function(e) {
                      var parsedData = JSON.parse(e.data);
                      var nowTime = new Date(parsedData.published_at);
                      var dt = document.getElementById("table");
                      var rows = dt.rows.length;
                      var rowN = dt.rows[1];
                      var cell1 = rowN.cells[0];
                      var cell5 = rowN.cells[4];
                      var cell6 = rowN.cells[5];
                      var cell7 = rowN.cells[6];


                 //for(var i=0;i<rows;i++) {
                //  var rowN = dt.rows[i];

                    //      var lastTime = new Date(rowN.cells[6].innerHTML);
                  //rowN.cells[5].innerHTML = parsedData.data;
                 // rowN.cells[6].innerHTML = parsedData.published_at;

                   // }
                  //}

                  $(table).ready(function(){
                  $('table tr').each(function(){
                  if($(this).find('th').eq(0).text() == 'eTrap 1'){
                  cell5.innerHTML = parsedData.coreid;
                  cell6.innerHTML = parsedData.data;
                  cell7.innerHTML = parsedData.published_at;
                  }
                  });
                  });
//}


                  }, false);
              },5000);
              window.setInterval( function () {

                  var eventName1 = "EVENT_SMART_TRAP";
                  var deviceID1 = "570040001951353338363036";
                  var accessToken1 = "fd4b398a359ad4c81c3589bb3d90ad5c3959bd91";

              var requestURL = "https://api.spark.io/v1/devices/" + deviceID1 + "/events/?access_token=" + accessToken1;

                  var eventSource = new EventSource(requestURL);

                  eventSource.addEventListener('open', function(e) {
                      console.log("Opened!"); },false);

                  eventSource.addEventListener('error', function(e) {
                      console.log("Errored!"); },false);

                  eventSource.addEventListener(eventName1, function(e) {
                      var parsedData = JSON.parse(e.data);
                      var nowTime = new Date(parsedData.published_at);
                      var dt = document.getElementById("table");
                      var rows = dt.rows.length;
                      var rowN = dt.rows[1];
                      var cell1 = rowN.cells[0];
                      var cell5 = rowN.cells[4];
                      var cell6 = rowN.cells[5];
                      var cell7 = rowN.cells[6];


                 //for(var i=0;i<rows;i++) {
                  //var rowN = dt.rows[i];

                    //      var lastTime = new Date(rowN.cells[6].innerHTML);
                  //rowN.cells[5].innerHTML = parsedData.data;
                 // rowN.cells[6].innerHTML = parsedData.published_at;

                   // }
                   $(table).ready(function(){
           $('table th').each(function(){
               if($(this).find('td').eq(0).text() == 'eTrap 2'){
                 cell5.innerHTML = parsedData.coreid;
                 cell6.innerHTML = parsedData.data;
                 cell7.innerHTML = parsedData.published_at;
               }
           });
       });      //}$(document).ready(function(){







//}


                  }, false);
              },5000);

                }


  </script>
    </body>
</html>

I have tried using this method, but I am getting those values only in the first row. It’s not showing on the row with respect to the etrap. Kindly help me to sort this issue.

Thanks,
Gowtham


#16

I edited your post to add the magic three-back-ticks-on-a-line markup that makes code readable.

Your code only updates the first row, because in the example I gave you, I set rowN to always be dt.rows[1].

I don’t completely understand how you are using these “etrap” labels, so you will have to figure that out. If the row to be updated is somehow selected by the parsed JSON data, then you will have loop over all the rows checking if each row’s first cell matches the one you are looking for. I don’t understand your code that compares for ‘eTrap 1’.