I am trying to fetch data from MySQL table that have 2 columns, Temperature and Value. I want to store these values to JSON and then to pass to the client side script. My PHP code is: database2json.php:
<?php
$con = mysql_connect("localhost", "root", "123456");
if (!$con) {
die('Could not connect:' . mysql_error());
}
mysql_select_db("klima", $con);
$result = mysql_query("select Dan, Temperatura from TEMPERATURA");
$niz = array();
while ($row = mysql_fetch_array($result)) {
$niz[$row['Dan']] = $row['Temperatura'];
}
mysql_close($con);
$obj = json_encode($niz);
echo $obj;
?>
When I run this file on server I get this:
{"1":"-1","2":"0","3":"0","4":"0","5":"4","6":"5","7":"3","8":"2","9":"2","10":"1","11":"-2","12":"-2","13":"0","14":"1","15":"-2","16":"-1","17":"-1","18":"-2","19":"-1","20":"3","21":"-1","22":"0","23":"1","24":"3","25":"1","26":"1","27":"-1","28":"-1","29":"4","30":"5","31":"5"}
That is what is expected.
Html is nothing special.
index.html:
<html>
<head>
<title>jQuery</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="custom.js" type="text/javascript"></script>
</head>
<body>
<div id="id1"></div>
</body>
</html>
Now I call php from jQuery and to show these values.
custom.js:
$(document).ready(function(){
$.post('database2json.php', function(data){
$('#id1').html(data);
},
"json");
});
This also gives same output like php:
{"1":"-1","2":"0","3":"0","4":"0","5":"4","6":"5","7":"3","8":"2","9":"2","10":"1","11":"-2","12":"-2","13":"0","14":"1","15":"-2","16":"-1","17":"-1","18":"-2","19":"-1","20":"3","21":"-1","22":"0","23":"1","24":"3","25":"1","26":"1","27":"-1","28":"-1","29":"4","30":"5","31":"5"}
Now I dont know how to convert this into array of [Dan, Temperatura]. I need this array to forward to chart and plot data (I am not asking about plotting, just to get array).
How to achieve this?