0

I'm trying to pass an array from php (on a separate file) side to JavaScript and update HTML table. The array on the php side is a result of MySQL query. Here is what I've done so far:

function updateSensorsTable() {
    $.getJSON("/getTableFromDB.php", function (json) {
     for (i = 0; i < 8;i++ )
         document.getElementById(i).innerHTML = json[i];
    });
}
<?php

include("connect_to_mysql.php");

$result = mysql_query("SELECT value FROM sens" );

while ($row = mysql_fetch_row($result)) {
    $php_array[]=$row[0];
}

echo json_encode($php_array);

?>
gvlasov
  • 18,638
  • 21
  • 74
  • 110
bardalas
  • 81
  • 1
  • 1
  • 10
  • The for loop from 0 to 7 looks a little bit dubious (use `json.length` instead?). But from what it looks like your PHP data is being sent to JS just fine. Is your question about how to build the table in JavaScript? – Halcyon Feb 10 '15 at 15:26
  • 2
    *"I hardly know php or **java**"* - [JavaScript and Java are different](https://www.java.com/en/download/faq/java_javascript.xml). I know you're probably shortening JavaScript to Java, and I'm probably being pedantic. (You have javascript tagged and refer to Java in your question) – ʰᵈˑ Feb 10 '15 at 15:26
  • `console.log( JSON.stringify(json) );` before the for shows what? – kero Feb 10 '15 at 15:27
  • Is that PHP syntax correct? I've never seen an array initialization like that before. I've always used the array() function. – tier1 Feb 10 '15 at 15:27
  • 3
    Please note that `mysql_*` functions shouldn't be used anymore, as [the extension is deprecated](http://stackoverflow.com/q/12859942/1230836) – Elias Van Ootegem Feb 10 '15 at 15:28
  • @tier1 yes. See: http://stackoverflow.com/questions/21633000/is-it-possible-to-use-an-array-without-initializing-it/21633074 - Introduced in [PHP 5.4](http://php.net/releases/5_4_0.php) – ʰᵈˑ Feb 10 '15 at 15:28
  • `$.getJSON` is a jquery method - are you including jquery? Where are you calling `updateSensorsTable()`? – billyonecan Feb 10 '15 at 15:30
  • @tier1 `$arr=[];` or `$arr=array();` is the same. – Alex Feb 10 '15 at 15:30
  • 1
    Access the php page `/getTableFromDB.php` directly from your browser to see if it outputs what it should output. That way you can tell if there is error in your php script or javascript. – Qwerty Feb 10 '15 at 15:31
  • @Alex Sure I get that. I guess I'm now questioning the scope of $php_array now as it doesn't exist outside of the loop – tier1 Feb 10 '15 at 15:33
  • @tier1 it has been treated as an array inside the loop `$php_array[]` – Alex Feb 10 '15 at 15:34
  • 1
    @tier1 [doesn't matter](https://eval.in/282615). There are no scope issues on a `while` loop. We're now on a tangent. Back to OP's question pls. – ʰᵈˑ Feb 10 '15 at 15:35
  • @Qwerty here is what `/getTableFromDB.php` shows when I run it from the browser: `["61","9","5","77","625","44414","3969453","1","1","57","50"]` – bardalas Feb 10 '15 at 15:47
  • @billyonecan I'm calling `updateSensorsTable()` from the javascript using `setInterval(updateSensorsTable, 2000);`. I'm not sure I included jquery - please explain where should I add what – bardalas Feb 10 '15 at 15:49
  • It's all here -> http://jquery.com/download/ – billyonecan Feb 10 '15 at 15:55
  • Still can't it working. I don't mind in which way to do this (json or other methood) all I need is to update the `document.getElementById(i).innerHTML` with values from DB – bardalas Feb 10 '15 at 16:31

2 Answers2

0

Don't forget to set the header :

header('Content-Type: application/json');

When you do "document.getElementById(i)" you try to access on an element witch having a bad ID (integer)... Here is the rule :

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Bang
  • 919
  • 4
  • 11
0

Here is the complete page

<script type="text/javascript"  >

     setInterval(updateSensorsTable, 2000);
     setInterval(updatePower, 1000);


     function showValue(value) {
         //show value in html
         document.getElementById("brightnesValue").innerHTML = value;
         //Set brightness value to DB id=10
         callPage('/setValueToDB.php?value=' + value + '& id=10' + '', document.getElementById(''));
     }

     function TurnLedOn() {
         //TODO: need to set the led state and update the sql server
         document.getElementById("ledStatus").src = "/LedOn.png";
         callPage('/setValueToDB.php?value=1&id=9' + '', document.getElementById(''));
     }

     function TurnLedOff() {
         //TODO: need to set the led state and update the sql server
         document.getElementById("ledStatus").src = "/LedOff.png";
         callPage('/setValueToDB.php?value=0&id=9' + '', document.getElementById(''));
     }

     function AjaxCaller() {
         var xmlhttp = false;
         try {
             xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
             try {
                 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
             } catch (E) {
                 xmlhttp = false;
             }
         }

         if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
             xmlhttp = new XMLHttpRequest();
         }
         return xmlhttp;
     }

     function callPage(url, div) {
         var ajax = AjaxCaller();
         ajax.open("GET", url, true);
         ajax.onreadystatechange = function () {
             if (ajax.readyState == 4) {
                 if (ajax.status == 200) {
                     div.innerHTML = ajax.responseText;
                 }
             }
         }
         ajax.send(null);
     }

      function updateSensorsTable() {
         
         for (i = 0; i < 8; i++) {
             callPage('/getVarFromDB.php?offset=' + i , document.getElementById(i));
         }
         /*
         $.getJSON("/getTableFromDB.php", function (json) {
             for (i = 0; i < 8;i++ )
             document.getElementById(i).innerHTML = json[i];
             });
             */
             }

     function updatePower() {
         callPage('/getVarFromDB.php?offset=' + 10, document.getElementById('powerValue'));
     }

 </script>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0"/>
        <title>SmartLight</title>
    </head>

    <body bgcolor="#E6E6FA">
        <br></br>
        <table class="sensorsTable" align="center">
            <thead>
            <tr >
                <th>Sensor</th>
                <th>Value</th>
            </tr>
            </thead>
            <tbody>
                <tr>
                    <td align="left">GPS</td>
                    <td align="center" id="0">0</td>
                </tr>
                <tr>
                    <td align="left">Temperature</td>
                    <td align="center" id="1">0</td>
                </tr>
                <tr>
                    <td align="left">Pressure</td>
                    <td align="center" id="2">0</td>
                </tr>
                <tr>
                    <td align="left">Light</td>
                    <td align="center" id="3">0</td>
                </tr>
                <tr>
                    <td align="left">Altitude</td>
                    <td align="center" id="4">0</td>
                </tr>
                <tr>
                    <td align="left">Accelerometer</td>
                    <td align="center" id="5">0</td>
                </tr>
                <tr>
                    <td align="left">Humidity</td>
                    <td align="center" id="6">0</td>
                </tr>
                <tr>
                    <td align="left">Camera</td>
                    <td align="center" id="7">0</td>
                </tr>
            </tbody>
        </table>

        <br></br>

         <table class="ledTable" align="center">
                     <tr>
                         <td align="center"><input type="image" src="/TurnOn.png"  id="turnOn" width="60" height="60" onclick='TurnLedOn()'></td>
                         <td align="center"><input type="image" src="/TurnOff.png" id="turnOff" width="60" height="60" onclick='TurnLedOff()'></td>
                         <td align="center"><img src="/LedOn.png" style="width:60px;height:60px" id="ledStatus"></td>
                     </tr>
                     <tr>
                                 <td align="center" id="ledOnButton">LED On</td>
                                 <td align="center" id="ledOffButton">LED Off</td>
                                 <td align="center">LED Status</td>
                     </tr>
         </table>

        <div align="center">
            Brightness:
            <input type="range" id="brightnesBar" min="0" max="100" value="0" step="1" onchange="showValue(this.value)" />
            <span id="brightnesValue">0</span>
            <table align="center" class="power">
                <tr>
                    <td align="center" id="powerValue">0</td>
                    <td align="left">mW</td>
                </tr>
            </table>
        <div align="center" >LED Power Meter</div>
        </div>
bardalas
  • 81
  • 1
  • 1
  • 10