Only can load one Zingchart - javascript

i have a problem that i can only load 1 zingchart in my web even though i have codes for 2 charts.
The code will just generate the latest chart, in this case, the pie chart and ignore the bar chart.
Below are my codes
<?php
//getDBConnect function
require 'dbconnect.php';
//Get ID from form
$id = $_GET['staffid'];
//connect to database
$con = getDBConnect();
if(!mysqli_connect_errno($con)){
$sqlQueryStr =
"SELECT a.ai_Name, r.duration " .
"FROM report AS r, academicinstitution AS a " .
"WHERE r.ai_Id = a.ai_Id ";
$result = mysqli_query($con,$sqlQueryStr);
mysqli_close($con);
} else {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get data into array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
//Group array by ai_Name
$grouparray = array();
foreach($emparray as $item)
{
if(!isset($grouparray[$item["ai_Name"]]))
$grouparray[$item["ai_Name"]] = 0;
$grouparray[$item["ai_Name"]] += $item["duration"];
}
?>
<script>
var dataBar=[
<?php
foreach($grouparray as $keys => $value){
echo $value. ",";
}
?>];
window.onload=function(){
zingchart.render({
id:'chartBar',
height:400,
width:600,
data:{
"graphset":[
{
"type":"bar",
"title":{"text":"BarChart"},
"series":[
{
"values":dataBar
}
]
}
]
}
});
};
</script>
<script>
var dataPie=[
<?php
foreach($grouparray as $keys => $value){
echo '{';
echo '"text":"'.$keys.'","values":['.$value.']';
echo '},';
}
?>];
window.onload=function(){
zingchart.render({
id:'chartPie',
height:400,
width:600,
data:{
"graphset":[
{
"type":"pie",
"title":{"text":"PieChart"},
"series":dataPie
}
]
}
});
};
</script>
<div id="chartBar"></div>
<div id="chartPie"></div>
What should i do?

The issue here is that you've assigned two functions to the window.onload event. JavaScript only allows one function to be called when that event fires. If you assign multiple functions to it, the latest assignment will overwrite any previous ones. That's why your pie chart is rendering but not your bar chart.
The solution is to put both render calls inside the window.onload callback.
Here's what that looks like:
<script>
var dataBar=[
<?php
foreach($grouparray as $keys => $value){
echo $value. ",";
}
?>];
var dataPie=[
<?php
foreach($grouparray as $keys => $value){
echo '{';
echo '"text":"'.$keys.'","values":['.$value.']';
echo '},';
}
?>];
window.onload=function(){
zingchart.render({
id:'chartBar',
height:400,
width:600,
data:{
"graphset":[
{
"type":"bar",
"title":{"text":"BarChart"},
"series":[
{
"values":dataBar
}
]
}
]
}
});
zingchart.render({
id:'chartPie',
height:400,
width:600,
data:{
"graphset":[
{
"type":"pie",
"title":{"text":"PieChart"},
"series":dataPie
}
]
}
});
}
</script>
I'm on the ZingChart team. Holler if you have any more questions.

Related

Insert MySQLi in JavaScript

I need help with FullCalendar and Javascript and PHP.
I need to include this foreach PHP code into this Javascript.
<script type="text/javascript">
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
events: [
<?php
$sql = "SELECT * FROM eventi";
$eventi = $mysqli->query($sql);
foreach ($users as $row) {
echo '{';
echo 'title: "'.$eventi['nome'] . '"';
echo 'start: "'.$eventi['data'] . '"';
echo '},';
}
?>
]
});
});
</script>
By changing your query so ite returns the data with the desired column names, and then using json_encode to format the results, you can
simplify the code quite a bit.
<script type="text/javascript">
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
events: [
<?php
$sql = "SELECT `nome` as `title`, `data` as `start` FROM eventi";
$eventi = $mysqli->query($sql);
$allrows = $eventi->fetch_all(MYSQLI_ASSOC);
$rslt = json_encode($allrows);
echo $rslt;
?>
]
});
});
</script>

Uncaught SyntaxError: Unexpected token < in CodeIgniter

I am currently working on CodeIgniter charts, but am getting an error like:
Uncaught SyntaxError: Unexpected token <
And charts are not loading showing blank.
var data_course_stats = google.visualization.arrayToDataTable([
['Course', 'Time spent',{ role: 'style' }],
<?php
$i=0;
foreach ($timespent_stats as $course) { $course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
$color_val = $colors[$i++];
?>
['<?php echo $course->title;?>', <?php echo $course->spent_seconds/60;?>,'<?php echo $color_val; ?>'],
<?php } ?>
]);
var options_course_stats = {
title: 'Course Wise Spent Time in Minutes',
curveType: 'function',
height: 400,
bar: {groupWidth: "50%"},
legend: { position: "none" },
};
For longer blocks, to keep PHP open - you're getting in trouble because you're mixing and matching open and closed. Change this:
<?php
$i=0;
foreach ($timespent_stats as $course) { $course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
$color_val = $colors[$i++];
?>
['<?php echo $course->title;?>', <?php echo $course->spent_seconds/60;?>,'<?php echo $color_val; ?>'],
<?php } ?>
to this:
<?php
$i=0;
foreach ($timespent_stats as $course) {
$course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats))) {
$color_val = $colors[$i++];
echo "['" . $course->title . "','" .
$course->spent_seconds/60 . "','" .
$color_val . "']";
}
}
?>
although you have accepted the answer, i want to add the another technique which is little simpler than the previous one. You can perform echo with <?= like <?php echo something; ?> so you can simply do this <?= something ?>
<?php
$i=0;
foreach ($timespent_stats as $course) {
$course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
{
$color_val = $colors[$i++];
?>
[<?= $course->title ?>, <?= $course->spent_seconds/60 ?>, <?= $color_val ?>]
<?php
}
}
?>
If anyone get this problem again, check if your base_url is correct in config/config.php

Ajax Dropdown to populate Province and City

I am using Ajax for my dropdown to select Province and City.
I wanted the City to be populated after I choose Province.
I already have my code but unfortunately it doesn't work.
Here are my codes
javascript
<script type="text/javascript">
function provChange(){
var province = $("#province_id").val();
$.ajax({
url: "<?php //echo $this->Html->url('/front/ajax_city_id'); ?>/"+province+"/<?php //echo $this->request->data('Car.city_id'); ?>",cache: false,
success: function(msg){$("#city_id").html(msg); },
"statusCode": {
403: function() {
window.location.href="<?php //echo $this->Html->url(array('controller'=>'front','action'=>'index')); ?>"
},
500: function() {
alert('Error Server Side occured');
}
}
});
}
</script>
view.ctp
<div class="emBeli form large-9 medium-8 columns content">
<?php echo $this->Form->input('provinsi',array('type'=>'select','empty'=>'Provinsi','options'=>$provinsis,'id'=>'province_id','class'=>'form-control form-control-custom','label'=>false,'onChange'=>'provChange()')); ?>
<?php echo $this->Form->input('kota',array('type'=>'select','empty'=>'Kota','options'=>$kota,'class'=>'form-control form-control-custom','label'=>false)); ?>
</div>
ajax_city_id.ctp
<?php
if ($key==null) echo "<option value=\"\">Kota</option>";
foreach($types as $i):
if($i['Kota']['id']==$key) echo "<option value=\"".$i['Kota']['id']."\" selected>".$i['Kota']['name']."</option>";
else echo "<option value=\"".$i['Kota']['id']."\">".$i['Kota']['name']."</option>";
endforeach;
?>
controller.php
public function ajax_city_id($id = null, $key = null, $cur = null)
{
$this->layout = 'ajax';
$this->set('types', $this->Kota->find('all', array('conditions' => array('display' => 1, 'Kota.province_id =' => $id), 'order' => array('Kota.name' => 'asc'))));
$this->set('key', $key);
}
all i got is ReferenceError: Can't find variable: $
which means it can't find variable $("#province_id") on my javascript code.
please somebody help......

How do I create a C3 Chart Line Graph from JSON data?

I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>

Javascript and PHP using For loop

I have the following code that will output a line chart as follows :
<script class="code" type="text/javascript">
$(document).ready(function(){
var line1=[['2008-08-12 ',14], ['2008-09-12 ',6.5], ['2008-10-12 ',5.7], ['2008-11-12 ',9], ['2008-12-12 ',8.2]];
var plot1 = $.jqplot('chart1', [line1], {
title:'Daily Sales',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer
}
},
series:[{lineWidth:4, markerOptions:{style:'square'}}]
});
});
</script>
The output for the above code is correct, but i want to insert a PHP loop to select data from mysql and place it insde var line1 as an array
So I created a test code as follows :
<script class="code" type="text/javascript">
$(document).ready(function(){
<?php
$date = date('Y-m-d');
for($i=1;$i<6;$i++){
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
?>
var line1=[['<?php echo $newdate; ?> ',<?php echo $i ?>]];
<?php
$date = $newdate;
}
?>
var plot1 = $.jqplot('chart1', [line1], {
title:'Daily Sales',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer
}
},
series:[{lineWidth:4, markerOptions:{style:'square'}}]
});
});
</script>
This outputs the last value which is 2015-5-16 and 5 all i want is to output all the result from 1 to 5 and having dates incremented by each month 2014-12-16 to 2015-5-16.
I hope this makes sense ! Thank You
You're doing this wrong. You don't use PHP to dump text into a Javascript code block directly. That's a sure-fire way of introducing a javascsript syntax error and killing the entire code block.
You build a native PHP structure (array, object, whatever) and then you json_encode() that.
e.g.
<?php
$results = get_data_from_db();
$data = array();
while($row = fetch_row_from_result($results)) {
$data[] = array($row['foo'], $row['bar']);
}
?>
<script type="text/javascript">
var data_from_db = <?php echo json_encode($data); ?>;
</script>
Replace your PHP-Block for "var line1=[['..." with this:
<?php
$date = date('Y-m-d');
$js = " var line1=[";
for($i=1;$i<6;$i++) {
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
if($i>1) { $js.= ", "; }
$js.= "['".$newdate." ',".$i."]";
$date = $newdate;
}
$js.= "];";
echo $js;
?>

Categories

Resources