I am using JQplots for rendering the piecharts.I have 2 piecharts.Individually they are working fine. But when I want them in a single page, they are overlapping on one another. Please let me know how can I show them one beside the other? Thanks in advance.
chart 1 code:
<!-- for jqplot graphs -->
<script src="../../assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="../../js/jqplot.js"></script>
<script type="text/javascript" src="../../assets/plugins/jqplot.pieRenderer.min.js"></script>
<link rel="stylesheet"href="../../css/graphs.css" type="text/css">
<!-- end of jqplot graphs js -->
<?php
/* Your Database Name */
$dbname = 'finalCMS';
/* Your Database User Name and Passowrd */
$username = 'root';
$password = 'password';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT ComplianceStatus,count FROM indexonboard WHERE zone='SEA' and country='SG'");
$rows = array();
foreach($result as $r) {
$rows[] = array( $r['ComplianceStatus'],(int)$r['count']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
print_r($jsonTable);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//mysql_close($conn);
$conn=null;
?>
<script>
function drawchart(){
//function drawchart()
var data1 =<?php echo $jsonTable;?>;
alert(data1);
var plot1 = jQuery.jqplot ('chartsg', [data1],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show:true, location: 'e' }
}
);
}
drawchart();
</script>
<div id="chartsg"></div>
The code for chart 2:
<!-- for jqplot graphs -->
<script src="../../assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="../../js/jqplot.js"></script>
<script type="text/javascript" src="../../assets/plugins/jqplot.pieRenderer.min.js"></script>
<link rel="stylesheet"href="../../css/graphs.css" type="text/css">
<!-- end of jqplot graphs js -->
<?php
/* Your Database Name */
$dbname = 'finalCMS';
/* Your Database User Name and Passowrd */
$username = 'root';
$password = 'password';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT Compliancestatus,value FROM COUNT_VALUE WHERE Zone='PZ' and country='AU' and `Compliancestatus` is not null
");
$rows = array();
foreach($result as $r) {
$rows[] = array( $r['Compliancestatus'],(int)$r['value']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
print_r($jsonTable);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//mysql_close($conn);
$conn=null;
?>
<script>
$(document).ready(function(){
//var data1=[
// ['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],
// ['Out of home', 16],['Commuting', 7], ['Orientation', 9]
// ];
var data1 =<?php echo $jsonTable;?>;
alert(data1);
var plot1 = jQuery.jqplot ('chart1', [data1],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show:true, location: 'e' }
}
);
});
</script>
<div id="chart1"></div>
query("SELECT ComplianceStatus,count FROM indexonboard WHERE zone='SEA' and country='SG'");
use different holders for both and fixed the width and height
<div id="piechartHolder" >
<div style="width:50%">
<span id="Chart1Title">Chart1</span>
<div id="chart1" style="width:100%">
</div>
<div style="width:50%">
<span id="Chart2Title">Chart2</span>
<div id="chart2" style="width:100%">
</div>
</div>
Try specifying div sizes, it should help
<div id="chart" style="height:300px; width:600px;"></div>
Related
I have meteorological data that I am retrieving through MySQL and can see it through phpMyAdmin. I am trying to plot stuff but I get no data in the plot.
My code is
<?php
// connect to database
$conn = mysqli_connect('localhost', 'root', 'station', 'meteobridge');
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
// write query for data
$sql = 'SELECT ID,TempInCur,TempOutCur FROM mystation';
$dateFormat = 'SELECT DateTime FROM mystation';
// make query & get result
$result = mysqli_query($conn, $sql);
$dtresult = mysqli_query($conn, $dateFormat);
// fetch the resulting rows as an array
$dailyMeasurements = mysqli_fetch_all($result, MYSQLI_ASSOC);
$dtArray = mysqli_fetch_all($dtresult, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'TempIn');
data.addColumn('number', 'TempOut');
data.addRows([
[ <?php $dtArray[0]['DateTime'] ?>, <?php echo $dailyMeasurements[0]['TempInCur'] ?>,<?php echo $dailyMeasurements[0]['TempOutCur'] ?>],
[ <?php $dtArray[1]['DateTime'] ?>,<?php echo $dailyMeasurements[1]['TempInCur'] ?>,<?php echo $dailyMeasurements[1]['TempOutCur'] ?>],
[ <?php $dtArray[2]['DateTime'] ?>,<?php echo $dailyMeasurements[2]['TempInCur'] ?>,<?php echo $dailyMeasurements[2]['TempOutCur'] ?>]
]);
var options = {
title: 'Temperaturas',
//curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
<?php include('templates/footer.php'); ?>
</html>
The values for $dailyMeasurements[*]['TempInCur'] are 27.1, and 28.7 for $dailyMeasurements[*]['TempOutCur']. And the values of $dtArray[0]['DateTime'] are 2020-12-27 16:58:26, 2020-12-27 17:03:28, 2020-12-27 17:08:31.
The reason I am adding data with only the first few indexes of my arrays is because when I tried using the whole array (a long time ago), I would have more errors without understanding the problems. I tried making a simple example where I could try to figure out as a beginner what's going on and what is wrong. That made it possible to even get the following image of the resulting dataless plot.
If you have a way to feed the arrays directly to Google charts then that's even better! My intention was to figure out that after I am able to produce a plot.
I'm not sure but you get an associative array.
You should convert this array to an object
const objDatas = JSON.parse($dtArray);
then
GoogleCharts.load("current", { packages: ['corechart'], callback: drawChart });
function drawChart() {
//use objDatas.yourProperty
It worked for me
first, the sql. it looks like all columns are coming from the same table,
so why not include them all in the same query...?
from...
$sql = 'SELECT ID,TempInCur,TempOutCur FROM mystation';
$dateFormat = 'SELECT DateTime FROM mystation';
to...
$sql = 'SELECT DateTime,TempInCur,TempOutCur FROM mystation';
next, build your array in php...
// make query & get result
$result = mysqli_query($conn, $sql);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = array($row['DateTime'], $row['TempInCur'], $row['TempOutCur']);
}
then write it to the page in the addRows method...
data.addRows(<?php echo json_encode($rows); ?>);
see following snippet...
<?php
// connect to database
$conn = mysqli_connect('localhost', 'root', 'station', 'meteobridge');
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
// write query for data
$sql = 'SELECT DateTime,TempInCur,TempOutCur FROM mystation';
// make query & get result
$result = mysqli_query($conn, $sql);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = array($row['DateTime'], $row['TempInCur'], $row['TempOutCur']);
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'TempIn');
data.addColumn('number', 'TempOut');
data.addRows(<?php echo json_encode($rows); ?>);
var options = {
title: 'Temperaturas',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
<?php include('templates/footer.php'); ?>
</html>
I am trying to build some ZingCharts with weatherdata from a homemade weatherstation. Currently I am using Google Charts, but would rather use Zing as it seems a whole lot easier to work with. Except, I can't get it to pull data from my Database. Below I have the demo example from ZingChart git, all I did was change the variables concerning my sql server. But it just shows an empty page. Looking at the page source after loading reveals that it doesn't fill the arrays with any data at all.
<!DOCTYPE html>
<html>
<head>
<title>MySQL Demo</title>
<script type="text/javascript" src="http://cdn.zingchart.com/zingchart.min.js"></script>
</head>
<body>
<script>
<?php
$host = "localhost";
$port = 3306;
$usernm = "pi";
$passwd = "";
$dbname = "weatherDB";
$query = "SELECT timestamp, temperature from bme680 ORDER BY id ASC";
$time = [];
$temperature = [];
$mysqli = new mysqli($host, $usernm, $passwd, $dbname, $port);
if($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')' . $mysqli->connect_error);
}
if ($result = $mysqli->query($query)) {
while( $row = $result->fetch_array(MYSQLI_NUM)){
array_push($time, $row[0]);
array_push($temperature, $row[1]);
}
$result->close();
}
?>
var dateValues = [<?php echo join($time, ',') ?>];
var seriesValues = [<?php echo join($temperature, ',') ?>];
<?php
$mysqli->close();
?>
</script>
<script>
window.onload=function(){
zingchart.render({
id:"myChart",
width:"100%",
height:400,
data:{
"type":"line",
"title":{"text":"Data Pulled from MySQL Database"},
"scale-x":{
"values": dateValues,
"transform":{
"type":"date",
"item":{
"visible":false
}
}
},
"plot":{"line-width":1},
"series":[ {"values":seriesValues}]
}
});
};
</script>
<h1>Database Data</h1>
<div id="myChart"></div>
</body>
</html>
I can't seem to get my button to work. the button will update mysql values when it is pressed. however, when i press the button, nothing happen. no logs appear on the console. did i miss something here?
the plan is to have a graph at the top and a table just below the graph. the graph will serve as a live graph.
the value in the table will toggle between on/off to simulate control of a water pump.
index2_2.php
<?php
require 'mysql.php';
?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="style.css" />
<!-- jQuery Script -->
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script>
// jQuery code
// jQuery code available after the page has fully loaded
$(".table #tbody1").on('click', ':button', function(){
id = $(this).prop("id");
console.log('button ' + id + ' pressed');
if($(this).prop('value') == 'ON'){
status = 'OFF';
}else{
status = 'ON';
}
// load table with updated values
$('#tbody1').load("mysql.php", {
id: id,
status: status
}, function(){
console.log('table loaded');
});
});
</script>
<script>
window.onload = function() {
var updateInterval = 2000;
var sensor1Data = [];
var sensor2Data = [];
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
title: {
text: "Soil Moisture Reading"
},
axisX: {
title: "chart updates every " + updateInterval / 1000 + " secs"
},
axisY:{
includeZero: false
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
verticalAlign: "top",
fontSize: 22,
fontColor: "dimGrey",
itemclick : toggleDataSeries
},
data: [{
type: "line",
name: "Sensor 1",
dataPoints: sensor1Data
},
{
type: "line",
name: "Sensor 2",
dataPoints: sensor2Data
}]
});
setInterval(function(){updateChart()}, updateInterval);
function toggleDataSeries(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
function updateChart() {
$.getJSON("http://192.168.1.3/Socket-4/getsensor.php", addData);
}
function addData(data){
// try using ID to filter new values.
// eg: newData[i].ID != oldData[i].ID
// only plot new data. shift graph when datapoints > than a value
for (var i = 0; i < data.length; i++) {
if(data[i].sensorName == 'sensor 1'){
sensor1Data.push({
x: new Date(data[i].Date),
y: Number(data[i].sensorValue)
});
}
if(data[i].sensorName == 'sensor 2'){
sensor2Data.push({
x: new Date(data[i].Date),
y: Number(data[i].sensorValue)
});
}
}
chart.render();
}
$.getJSON("http://192.168.1.3/Socket-4/getsensor.php", addData);
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div class="table">
<table>
<thead>
<tr>
<th>ID:</th>
<th>Name:</th>
<th>Status:</th>
</tr>
</thead>
<tbody id='tbody1'>
<?php
getValues();
?>
</tbody>
</table>
</div>
</body>
</html>
mysql.php
<?php
require_once 'mysqldb.php';
include 'socket.php';
if(isset($_POST['id']) and isset($_POST['status'])){
$id = $_POST['id'];
$status = $_POST['status'];
updateValues($id, $status);
getValues();
}
function getValues(){
/*
This function retrieves the values from the database
and store it in an array.
*/
global $db_host, $db_user, $db_pass, $db_name;
$data = array();
/* start connection */
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = 'SELECT * FROM actuator ORDER BY ID';
if($query = mysqli_query($conn,$sql)){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$data[] = $row;
// Display into html table
echo "<tr>";
echo "<td>{$row['ID']}</td>";
echo "<td>{$row['name']}</td>";
echo "<td>
<input type='button' id='{$row['ID']}' value='{$row['value']}' name='{$row['name']}'>
</td>";
echo "</tr>";
}
/* free result set */
mysqli_free_result($query);
}
/* close connection */
mysqli_close($conn);
socket($data);
}
function updateValues($id, $status){
/*
This function updates the database with
values retrieved from POST.
*/
global $db_host, $db_user, $db_pass, $db_name;
/* start connection */
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
// Prevent SQL injection
$status = mysqli_real_escape_string($conn, $status);
$id = mysqli_real_escape_string($conn, $id);
// $sql = "UPDATE actuator SET value='$status' WHERE ID=$id";
$sql = "INSERT INTO led_control (ID, value, name) VALUES ('$id', '$status', 'water pump')";
mysqli_query($conn,$sql);
/* close connection */
mysqli_close($conn);
}
?>
maybe the event handler
$(".table #tbody1").on('click', ':button', function(){
is called before the button is rendered.
Put the Handler inside of
$( document ).ready(function() {
like
<script>
$( document ).ready(function() {
// jQuery code
// jQuery code available after the page has fully loaded
$(".table #tbody1").on('click', ':button', function(){
id = $(this).prop("id");
console.log('button ' + id + ' pressed');
if($(this).prop('value') == 'ON'){
status = 'OFF';
}else{
status = 'ON';
}
// load table with updated values
$('#tbody1').load("mysql.php", {
id: id,
status: status
}, function(){
console.log('table loaded');
});
});
});
</script>
you can change echo like
echo "<td>
<input type='button' id='{$row['ID']}' value='{$row['value']}' name='{$row['name']}' onClick=test({$row['ID']})>
</td>";
and script:
function test(index){
....
}
or
echo "<td>
<input class = 'nameofclass' type='button' id='{$row['ID']}' value='{$row['value']}' name='{$row['name']}' onClick=test({$row['ID']})>
</td>";
$('table#tbody1').on('click','button.nameofclass',function(e) {
I'm going to use the real-time temperature values stored in MariaDB server to show real-time graphs on the web.
(Temperature values continue to accumulate in real time once every 5 seconds.)
Through a lot of trial and error, I decided that Highcharts.js would be the best tool for drawing graphs.
https://www.highcharts.com/stock/demo/dynamic-update
The link above is the demo source I used.
What I've been trying to do in the most
I've been putting a lot of things into the bar y.
I tried various things in the data.push of series.
(I'm a beginner on coding......)
I didn't know what I typed wrong, so I entered everything. I'm sorry.
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script type="text/javascript"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script>
Highcharts.stockChart('container', {
chart: {
events: {
load: function() {
var series = this.series[0];
setInterval(function() {
$(document).ready(function() {
var url = "https://---include json---.php";
$.getJSON(url, function(json) {
var val= json;
var temp1=(json['temp'][(Object.keys(json['temp']).length)-1]['temp1']);
console.log(json['temp'][(Object.keys(json['temp']).length)-1]['temp1']);
})});
var x = (new Date()).getTime() // current time
var y = temp1;
Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);//연속
}, 1000);
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title: {
text: 'TEST test'
},
exporting: {
enabled: true
},
credits:{
enabled:false
},
series: [
{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
y;
for (i = -999; i <= 0; i += 1) {
data.push([
//time + i * 1000,
//Math.round(Math.random() * 100)
]);
}
return data;
}())
}]
});
</script>
The following php code is the php code for json data.
<?php
//Creating Array for JSON response
$response = array();
$servername = "localhost";
$username = "";
$password = "!";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM temp2 order by id asc";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$response["temp"] = array();
while($row = mysqli_fetch_array($result)) {
$temp = array();
$temp["temp1"] = $row["temp1"];
array_push($response["temp"], $temp);
}
echo json_encode($response,JSON_NUMERIC_CHECK);
} else {
echo json_encode("0 results",JSON_NUMERIC_CHECK);
}
mysqli_close($conn);
?>
The above code values are output as shown below.
{"temp":[
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.82},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":18.05},{"temp1":17.93},{"temp1":17.82},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.82},{"temp1":18.05},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93}
]}
If you run the code, the graph won't appear on the screen.
I don't know how to print out json's value on the graph.
I translated it using Google translation because I am not good at English. I would like to thank you all for your reply.
Add a content type to the header:
<?php
header("Content-type: application/json; charset=utf-8");
You can use chart.js library. Simple and powerful
https://www.chartjs.org
Here are some example how to use:
https://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/
First of all: Wellcome to SO :)
I think you have the wrong Dataformat for your Data. You have a Array of Objects
[{"temp1":17.93},....]
But the example say:
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
An Array of Array. Try this:
<?php
//Creating Array for JSON response
$response = array();
$servername = "localhost";
$username = "";
$password = "!";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM temp2 order by id asc";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$response["temp"] = array();
while($row = mysqli_fetch_array($result)) {
$response["temp"][] = array("temp1", $row["temp1"]); // <-- change this line
}
echo json_encode($response,JSON_NUMERIC_CHECK);
} else {
echo json_encode("0 results",JSON_NUMERIC_CHECK);
}
mysqli_close($conn);
?>
I generated some Json data from Mysql Database with PHP as below:
equipments.php
<?php
require("config.inc.php");
//initial query
$query = "Select * FROM equipment";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Equipment Available!";
$response["equipments"] = array();
foreach ($rows as $row) {
$post = array();
$post["EquipmentId"] = $row["EquipmentId"];
$post["Name"] = $row["Name"];
$post["Ip"] = $row["Ip"];
$post["Brand"] = $row["Brand"];
$post["Location"] = $row["Location"];
//update our repsonse JSON data
array_push($response["equipments"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Equipment Available!";
die(json_encode($response));
}
?>
this returned the following data:
//localhost/equip/equipments.php (on my local apache server)
{
success: 1,
message: "Equipment Available!",
equipments: [
{
EquipmentId: "1",
Name: "UCH-NET",
Ip: "172.16.32.4",
Brand: "Engenius",
Location: "Top of ITD"
},
{
EquipmentId: "2",
Name: "UCH-PHOUSE",
Ip: "172.16.32.5",
Brand: "Mikrotik",
Location: "Top of ITD"
},
{
EquipmentId: "3",
Name: "UCH-SON",
Ip: "172.16.32.9",
Brand: "MIkrotik",
Location: "SON"
},
{
EquipmentId: "4",
Name: "UCH-GERIATRIC",
Ip: "172.16.32.10",
Brand: "Mikrotik",
Location: "Geriatric"
}
]
}
But when i try to use the returned Json like this in my AngularJS application no data is returned in the web page
services.js
'use strict';
var equipServices = angular.module('equipServices', ['ngResource']);
equipServices.factory('Equip', ['$resource',
function($resource){
return $resource( '/equip/equipments.php/');
}]);
equipment.js
function EquipmentsCtrl ($scope, Equip) {
$scope.setActive('equipments');
$scope.sidebarURL = 'partials/equipment.html';
$scope.currentEquipment = null;
$scope.setEquipment = function (EquipmentId) {
$scope.currentEquipment = $scope.equipments[EquipmentId];
};
$scope.equipments = Equip.query();
}
}
index.html
<title>IP Library</title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/controllers/app.js"></script>
<script type="text/javascript" src="js/controllers/equipments.js"></script>
<script type="text/javascript" src="js/controllers/admins.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/services.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.min.css">
</head>
<body>
<div class="container" ng-controller="AppCtrl" >
<h1>IP Library</h1>
<ul class="nav nav-pills">
<li ng-class="equipmentsActive">
<a href="#equipments" >Equipments</a>
</li>
<li ng-class="adminsActive">
Administrators
</li>
</ul>
<div ng-view></div>
</div>
</body>
</html>
Is there something wrong with the way I am calling the php generated Json in my services.js?
Thanks
Use Equip.get() instead of Equip.query() because you are getting from server an object, not an array:
Equip.get(function(result){
if(result.success === 1) // isn't better to return boolean?
$scope.equipments = result.equipments;
// else handle error
});