jquery button not executing - php

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) {

Related

Cannot pass PHP JSON encoded data via .Ajax call to HighCharts

I have PHP program to pull data from a MS SQL Server and encode the result in JSON
Here is the code below ->
<?php
/*
connect to MS SQL Server using PHP
*/
$serverName = "192.168.0.4,14333"; // ip:port
$connectionInfo = array( "Database"=>"YYY", "UID"=>"XX", "PWD"=>'XX');
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br /><pre>";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "
SELECT * FROM projections_sample
";
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
die(FormatErrors(sqlsrv_errors()));
$rows1 = array();
$rows1['name'] = 'Revenue';
while ($r1 = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC))
{
$rows1['data'][] = $r1['revenue'];
}
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
die(FormatErrors(sqlsrv_errors()));
$rows2 = array();
$rows2['name'] = 'Overhead';
while ($r2 = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC))
{
$rows2['data'][] = $r2['overhead'];
}
sqlsrv_free_stmt($getResults);
$result = array();
array_push($result,$rows1);
array_push($result,$rows2);
echo json_encode($result, JSON_NUMERIC_CHECK);
sqlsrv_close($conn);
?>
The results seem to be okay(I pasted the results into a JSON file (data.JSON) and pulled the results into highcharts)
The JSON results are not being pulled when the following code is used -
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Dynamic Chart</title>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="container" style="min-width: 155px; height: 500px; margin: 0 auto"></div>
<script>
let titleText = ' Revenue Vs Overhead'
let categoryLabels = ['Jan','Feb','Mar','Apr','May',Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
let yAxisText = 'Delta';
$(document).ready(function(){
$.ajax({
datatype: "json",
url: "data.php",
success: function(result)
{
Highcharts.chart('container', {
chart: {
type: 'line'
},
credits: {
enabled: false
},
title: {
text: titleText
},
xAxis: {
categories: categoryLabels
},
yAxis: {
min: 0,
title: {
text: yAxisText
}
},
series: result
});
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); //End Ajax Call
});
</script>
</body>
</html>
When I run the code I get a blank web page.

Update Datatable with Db records returned from AJAX Request

I have a very basic HTML Table. The data is from the database. I have now set up a datepicker with a button and as soon I click the button I do a AJAX request to get specific data for a specific date. (To make it easier my query just looks for id=1 as an example). I now want to return the data abnd update the datatable, but unfortunately the data is returned, but not shown.
data […]
0 {…}
id 1
category_id 1
title Technology Post One
This above is what gets returned. Am I doing a mistake in the format of the above or how do I update the datatable? I get the following error:
DataTables warning: table id=example - Requested unknown parameter '0' for row 0, column 0
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM posts WHERE id = 1";
result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
echo "0 results";
}
$conn->close();
$msg = ["data" => $rows];
// handle request as AJAX
echo json_encode($msg);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Practise</title>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20 js/jquery.dataTables.js"></script>
</head>
<body>
<?php
$sql = "SELECT * FROM posts";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$conn->close();
?>
<table id="example" border="1"><thead>
<th>id</th>
<th>title</th>
<th>created at
<p>Date: <input type="text" id="datepicker"><button>Click</button> </p>
</th>
</thead>
<?php
foreach ($rows as $value){
echo '<tr>';
echo '<td>'.$value['id'].'</td>';
echo '<td>'.$value['title'].'</td>';
echo '<td>'.$value['created_at'].'</td>';
echo '</tr>';
}
echo '</table>'
?>
</body>
<script>
$(document).ready(function() {
$('#example').DataTable({
"columns": [
{"data": "id"},
{"data": "author"},
{"data": "created_at"}
],
},
);
$( "#datepicker" ).datepicker();
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
created_at: $("#datepicker").val()
},
success: function(data) {
$('#example').DataTable().ajax.reload();
},
error: function(result) {
alert('error');
}
});
});
} );
You can update the js script and create a new php file for ajax call which will return the new datatable. Try out this code it will work -
<script>
var created_at = '';
$(document).ready(function() {
var datatable = $('#example').DataTable({
'processing': true,
'scrollX': true,
'serverSide': true,
'serverMethod': 'post',
'searching' : true,
'ajax': {
url:'new-file.php',
data: function(data){
data.created_at = created_at;
}
},
"columns": [
{"data": "id"},
{"data": "author"},
{"data": "created_at"}
],
});
$( "#datepicker" ).datepicker();
$("button").click(function(e) {
e.preventDefault();
created_at = $("#datepicker").val();
datatable.draw();
});
} );
</script>

How to get data from a DB(MySQL) and draw real-time graphs from a highcharts

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);
?>

How to display data from database by getting inputs from user in php mqsql? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How to display data from database by user specified date range and also comparing user input value with database field value.
The query is like this:
$sql = "SELECT * FROM table WHERE date between '".$date_min"' AND '".date_max"'";
assuming $date_min and $date_max are the values of your user input, and table the DB table where you want to query.
The php will be something like:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM table WHERE date between '".$date_min"' AND '".date_max"'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
Provided you made the part for user input.
These is from http://www.w3schools.com/php/php_mysql_select.asp.
Some research before making a question is required.
Regards
Now, you could try something like this, using an ajax request (jQuery required):
JS:
/**
* Created by evochrome on 26-3-2016.
*/
$( document ).ready(function() {
var timer;
$('#reset').click(function(e) {
$('input').val(""); //set value equal to zero
});
$('input').on("input", function (e) {
clearInterval(timer);
timer = setTimeout(getTableContents,2000);//Execute function `getTableContents` after 3s
});
});
function getTableContents() {
$('td').fadeOut(500, function(){ $(this).parent().remove();});
setTimeout(function() {
var inputs = {};
$(".theader input").each(function () {
if ($(this).val() != '') {
inputs[$(this).attr('name')] = $(this).val();
}
});
$.ajax({ //ajax request
method: "POST",
url: "../php/fetch.php",
data: inputs,
dataType: 'json',
cache: false,
success: function (data) {
var tmpObject = {};
var i = 0;
data.forEach(function (row) {
var obj = data[i];
$('table').append("<tr id='t" + i + "'></tr>");
Object.keys(obj).forEach(function (key) {
$('#t' + i).append("<td style='display: none;'>" + row[key] + "</td>");
});
i++
});
$('td').fadeIn(500);
}
})
}, 500);
}
CSS:
table {
width: 80%;
}
td {
width: 40%;
background-color:green;
height: 40px;
text-align: center;
}
.theader{
width:100%;
justify-content:space-around;
display:flex;
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>T-Test</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Input Some Data</h1>
<div class="theader">
<input name="FromDate" type="date"/>
<input name="ToDate" type="date"/>
<button id="reset">Reset</button>
</div>
<table>
<tr>
<td>2</td>
<td>John</td>
<td>Appleseed</td>
</tr>
</table>
<script src="js/jquery-2.2.0.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
PHP:
<?php
/**
* Creator: evochrome
* Date: 26-3-2016
* Time: 15:40
*/
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', '1');
$conn = new mysqli('localhost', $db_name, $db_password, $db_user);
if (! $conn){
echo 'Oh damn a crash!';
die(' Connection failed :(');
}
$fields = array(
'FromDate', 'ToDate'
);
$where = "1=1"; //true
foreach ($fields as $field) {
if ($value = $_POST[$field]) {
$where .= " AND $field = '$value'"; //for each field add clause
}
}
$query = $conn->query("SELECT * FROM $table_name WHERE $where"); //insert tablename and where clause
$array = array();
while($row = $query->fetch_assoc()){ //fetch from db
$array[] = $row;
}
echo json_encode($array);
$query->close();
$conn->close();

how to render multiple jqplot's pie charts in single page

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>

Categories