3

I am really stuck with my webpage that I would like to display gauges on, which update themselves with new data from a MySQL database. I have a couple of files to get it to work but it doesn't work. The first file is called data.php and it contains (sorry, comments in Dutch):

    <?php

    // Datum aanmaken om bovenaan de pagina te zetten
    date_default_timezone_set('Europe/Amsterdam');
    $vandaagtijd = date("d-m-Y, H:i");

    include_once "/externalpw/mysql_pw.php";
    $link = mysql_pconnect($MyHostname, $MyUsername, $MyPassword) or die("Error verbinden met DB: " . mysql_error());


    //Eerst de elektra en het gas selecteren in die database en dan daarmee aan de gang
    $db = mysql_select_db("elekgas", $link);
    if (!$db) {
            mysql_close($link);
            die("Error selecteren DB: " . mysql_error());
    }

    // Actuele waaarden op van huidig verbruik en meterstanden
    $result1 = mysql_query("SELECT gebr_laag_tarief AS glt, gebr_hoog_tarief AS ght, leve_laag_tarief AS llt, leve_hoog_tarief AS lht, huidig_verbruik AS hv, huidig_levering AS hl, gas FROM meetwaarden ORDER BY id DESC LIMIT 1");

    if (!$result1) {
            mysql_close($link);
            die("Error met query1: " . mysql_error());
    }
while ($row = mysql_fetch_assoc($result1)) {
        $data[] = $row;
}

?>

var jsonarray = <?php echo json_encode($data); ?>;

In the second file, my main file, I have this section to refresh the php output:

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$.post('index4.php'), function(data){
$(data.result).each(function(i, item){
$.append("<?= $" + item.key + " = " + item.value + "; ?>");
});
}, "jsonp");
});
</script>

My div to refresh contains basically nothing. I just want to return a new value for the gauges. The gauges themselves will use an interval function to update themselves. That gauge-code is below for clarity. What happens, however, it returns NaN (Not a Number). I have the feeling in need to imply some JSON_encode here to get it all working but I have no clue as how to get it going.

In the data.php echo JSON_encode($result1); seems a good start but then how to get it out in the main file? Obviously, the load('data.php') is not the way to go here...

<canvas id="gauge2"
     width="200" height="200"
     data-type="canv-gauge"
     data-title="Vermogen"
     data-min-value="0"
     data-max-value="400"
     data-major-ticks="0 100 200 300 400"
     data-minor-ticks="5"
     data-stroke-ticks="true"
     data-units="kWh"
     data-value-format="3.2"
     data-glow="true"
     data-animation-delay= false
     data-animation-duration=
     data-animation-fn=
     data-colors-needle="#dd0000 #0000ff"
     data-highlights="0 100 #a9feff, 100 300 #bbffaa, 300 400 #ffffaa"
     data-onready="setInterval( function() { Gauge.Collection.get('gauge2').setValue(<?= $hl; ?>);}, 5000);">
    </canvas>

I do know these questions have come by multiple times but I am not really a star as it comes to AJAX and JSON. So all help is appreciated! Thanks.

Arjan_IO
  • 175
  • 1
  • 9

2 Answers2

3

You should use jQuery's post in JS and json_encode in PHP.

Once you have a complex JSON object, read Access / process (nested) objects, arrays or JSON to understand how to access its items, then try this JSFiddle example I wrote for you, that gets a list of songs from iTunes' public API and put them in a table.

Community
  • 1
  • 1
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • 1
    Thanks for the reply, I changed my php into `while ($row = mysql_fetch_assoc($result1)) { $data[] = $row; }` and then using `var jsonarray = ;`. This seems to work as in my main file I get echoed `var jsonarray = [{"glt":"130", (....)`. So now I need to find out how to get it into the part that the gauges need :| – Arjan_IO Jan 26 '16 at 09:52
  • I came to ` ` But this as far as I get it going. Now I need to covert it back to either a php value (integer one to prevent NaN) or a var (also integer) and pass one of the two on to the gauges. Can you please help me as the examples I can find to not give me a clear answer :( – Arjan_IO Jan 26 '16 at 10:54
  • @Alession I followed your fiddle. The difference is that you use item.artworkUrl30 which is used multiple times in your link. Also, the first link uses an array where they use Name => john, Age => 32, Name => Doe, Age =>31. My array doesn't have a common identifier like artworkUrl30, Name or Age. This is also the reason I keep getting stuck when viewing examples. Maybe I just don't see it and my array does have a common identifier which I can call and store in a variable but I just don't get it ;( – Arjan_IO Jan 26 '16 at 12:30
  • @Arjan_IO then you have to create a working JSFiddle (where server result are contained inside a JSON-array), to clarify what your purpose is. – Alessio Cantarella Jan 26 '16 at 14:11
  • I edited my OP. When I now include data.php in my main file I see a line that states: `var jsonarray = [{"glt":"130",ght":"110",llt":"0",lht":"0",hv":"2130",hl":"0",gas":"10"}]` So this is the array that comes from my data.php file when I run my query. The strings glt, ght etc are basically the columns in my database, the numbers are the values (of the last row) stored in each column. Hope this helps. I never used jsfiddle before to set something up. All the file are hosted locally at the moment so can't link to them either. – Arjan_IO Jan 26 '16 at 14:19
  • If your JSON object is like this: `var data = [ { glt: 130 }, { ght: 110 }, { llt: 0 }, { lht: 0 }, { hv: 2130 }, { hl: 0}, { gas: 10 } ];`, then you can access `glt` as `data[0].glt`, `ght` as `data[1].ght`, etc. – Alessio Cantarella Jan 26 '16 at 14:43
  • I get exactly the text I posted. So only one pair of { }. I think I give up. I am just not good enough in this and it looks like unless I get a working code posted my brain just can't get around it. – Arjan_IO Jan 26 '16 at 15:14
  • Your `jsonarray` has many syntax errors. You have to correct them in PHP before you can handle it with JS. – Alessio Cantarella Jan 26 '16 at 15:20
  • Seems like valid output to me compared to http://php.net/manual/en/function.json-encode.php (the [ ] are gone btw). Just looks like the numbers are passed on as string since they are between " " . – Arjan_IO Jan 26 '16 at 16:12
  • Your `jsonarray` is not valid: it misses a `"` before every key except `glt`. – Alessio Cantarella Jan 26 '16 at 16:27
  • Apologies indeed. Didn't spot that. Now I get this `{"glt":"166","ght":"174","llt":"0","lht":"0","hv":"0","hl":"0","gas":"42"}` And I tried this: `$(document).ready(function() { $.ajaxSetup({ cache: false }); $.post("index4.php", function(data) { $(data.results).each(function(i) { var glt = i.glt; alert(glt); }); }, "jsonp"); });` I tried an alert on the end to see if any value is displayed but there is no alert let alone a value... – Arjan_IO Jan 26 '16 at 16:54
  • According to JavaScript Object Notation (you should study it before using it!), in your case `jsonarray` is an array (`[]`) of objects (`{}`), so to access its first element you have to cycle `jsonarray[0]`: `for (i in jsonarray[0]) console.log(jsonarray[0][i]); }`. – Alessio Cantarella Jan 26 '16 at 17:24
  • Because I am in the need of integers here, I changed it all slightly. The `var jsonarray`- bit is gone. Instead, inside the php-tags I just use `echo json_encode($data, JSON_NUMERIC_CHECK);`. Array now looks shows: {"glt":166,"ght":174,"llt":0,"lht":0,(...)}. We can clearly see that numbers are actually integers. Now for the extraction bit in the main file. I have read the Object Notation bit. But due to the shear lack of knowledge it doesn't make much sense. I tried modifying the code to `$.ajax({ type: "POST", url: "index4.php", success: function(data){ glt = data[0]; alert(glt);` No luck... – Arjan_IO Jan 26 '16 at 19:07
  • Would this be better to work with? `[{"0":"166","glt":"166","1":"174","ght":"174","2":"0","llt":"0","3":"0","lht":"0","4":"0","hv":"0","5":"0","hl":"0","6":"42","gas":"42"}]`? – Arjan_IO Jan 26 '16 at 20:49
1

To make things easy I post my solution here.

PHP-file:

while ($row = mysql_fetch_array($result1)) {
        $data = $row;

}

//echo json_encode($data, JSON_NUMERIC_CHECK);

array_push($json, $data);
echo json_encode($json);

?>

JS-part:

<script type="text/javascript">
var glt;
var ght;
var llt;
var lht;
var hv;
var hl;
var gas;

$(document).ready(function() {
$.ajax({
        type: "POST",
        url: "data.php",
        dataType: "JSON",
        success: function(data){
        glt = data[0].glt;
        ght = data[0].ght;
        llt = data[0].llt;
        lht = data[0].lht;
        hv  = data[0].hv;
        hl  = data[0].hl;
        gas = data[0].gas;
}
});
});
</script>

Gauge-part is just using the correct variable I want to display.

Massive thanks to Alessio Cantarella for his help though. He did point me in the right direction in the end :)

Arjan_IO
  • 175
  • 1
  • 9