0

I have the below data in array with two sub-arrays 0 and 1. I am trying to load only sub-array data 0 or 1 every time via json_encode:

My php code in my website:

<?php
    $dataPoints_temp = array(array(),array());
    $row = 1;
    
    if (($handle = fopen($latestFile, "r")) !== FALSE) {
        $data = array();
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            list($id, $time, $room, $pressure, $humidity, $pm2m5, $pm1m0) = $data;
            if ($id == "client1") {
                array_push($dataPoints_temp[0], array("x" => $data[0], "y" => $data[2]));
            } else if ($id == "client2") {
                array_push($dataPoints_temp[1], array("x" => $data[0], "y" => $data[2]));
            }
        }
    }
?>

My javascript in my website does now the following:

<script>
    window.onload = function() {
        var updateInterval = 1500;
        var $id = 0;
        var $dataPoints1 = <?php echo json_encode($dataPoints_temp[0], JSON_PRETTY_PRINT | JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK); ?>;
...
}
</script>

This works and I do get my graph working. The think that I am trying now is to make the $dataPoints_temp[0] more general to be able to select 0 or 1 as data points for the graph.

    var $dataPoints1 = <?php echo json_encode($dataPoints_temp[$id], JSON_PRETTY_PRINT | JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK); ?>;

But this gives me a lot of errors in the console of the browser although the $id is defined and for the moment set to 0.

Try suggestion from @Wimanicesir, I am storing all the data in one php array and use the json_encode to store this to a javascript array and then trying to use JSON.parse for this array, but I am getting an error, see.

client data:

(5) […]
  0: {…}
    ​​hum: 38.31
    ​​id: "51df"
    ​​pm1m0: 1
    ​​pm2m5: 1
    ​​pres: 1008.25
​​    temp: 22.24
    ​​<prototype>: Object { … }
  ​1: Object { id: "51df", temp: 22.24, pres: 1008.26, … }
...

See code:

var $rawData = <?php echo json_encode($client, JSON_PRETTY_PRINT | JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK); ?>;
var $obj = JSON.parse($rawData);

Console error:

 SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

Two more tries:

  1. $client value is as expected from php json_encode:

var $test1 = [{"hum": 38.31, "id": "51df", "pm1m0": 1, "pm2m5": 1, "pres": 1008.25, "temp": 22.24}];

  1. $client value represents the data as string:

var $test1 = '{"hum": 38.31, "id": "51df", "pm1m0": 1, "pm2m5": 1, "pres": 1008.25, "temp": 22.24}';

The rest of the test code:

var $test2 = JSON.parse($test1);
console.log($test2);

In the above two cases only the at the 2nd point the JSON.parse is successful! Does this mean that JSON.parse needs a string as input?

Update after a further investigation:

var $rawData = <?php echo json_encode($client, JSON_PRETTY_PRINT | JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK); ?>;
var $json = JSON.stringify($rawData);
var $dataPoints = JSON.parse($json);

const clients = [... new Set($dataPoints.map(data => data.id))]; // find all unique clients id's, which are two in the sample data '51df' & '51ff'

var $dataPoints1 = [];
var $dataPoints2 = [];
var $dataPointsHum = [];
var $dataPointsP2m5 = [];
var $dataPointsP1m0 = [];
var $clientId = 0; // we want the data for client 0
for (i = 0; i < $dataPoints.length; i++) {
    if (clients[$clientId] == $dataPoints[i].id) { // load data only for client based on $clientId
        var tuple1 = {x: $dataPoints[i].id, y: $dataPoints[i].temp};
        $dataPoints1.push(tuple1);

        var tuple2 = {x: $dataPoints[i].id, y: $dataPoints[i].pres};
        $dataPoints2.push(tuple2);

        var tuple_hum = {x: $dataPoints[i].id, y: $dataPoints[i].hum};
        $dataPointsHum.push(tuple_hum);

        var tuple_p2m5 = {x: $dataPoints[i].id, y: $dataPoints[i].pm2m5};
        $dataPointsP2m5.push(tuple_p2m5);

        var tuple_p1m0 = {x: $dataPoints[i].id, y: $dataPoints[i].pm1m0};
        $dataPointsP1m0.push(tuple_p1m0);
    }
}

The above code seems to works fine tested on a sample of data with two clients.

How can I do that?

Thanks

FotisK
  • 1,055
  • 2
  • 13
  • 28
  • You use a JS variable to access something in your PHP. This can not be done like that. Combining JS and PHP like that is also not recommended. To solve current problem, create a variable in PHP with the value of your id. – Wimanicesir Apr 06 '21 at 12:20
  • Hm, I guess my problem is that i can't fire up again `window.onload` again since the website is already loaded. Because the graph of client1 should shown in tab1 and for client2 on tab2 and switching tabs doesn't run again `window.onload`! – FotisK Apr 06 '21 at 12:45
  • If it's on the same page then load the full array from PHP into your JS. Then access it there with json.parse(). With other words, use your PHP mainly to pass your data and access and parse it with JS. – Wimanicesir Apr 06 '21 at 19:21
  • I have updated my question with a try following your suggestion but I am getting an error for `JSON.parse`. What am I doing wrong? – FotisK Apr 09 '21 at 22:31
  • `JSON.parse` Does indeed expect a `String` as input. Do you happen to know what JSON stands for? It stands for **J**ava**S**cript **O**bject **N**otation. When you call `json_encode` in PHP you are creating a `string` that would pass for actual valid JavaScript syntax. So when you do `var $rawData = ;` you are actually just writing out the declaration of a JavaScript object. Just be sure that there aren't any special PHP classes in there that would make the JS interpreter freak out. – Alain Doe Apr 10 '21 at 17:30
  • I have updated my question body with a solution that seems to work now. – FotisK Apr 12 '21 at 09:54

0 Answers0