I'm trying to draw an organizational chart (http://goo.gl/wgftfO) from JSON (php - mysql) but it doen'st display well.
Here is my HTML code:
<script type="text/javascript">
google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback(drawChart);
function json(){
$.ajax({
type: "POST",
url: "function/ver.php",
success: function(datos){
datos = eval(datos);
for (var i=0;i<datos.length;i++){
var id = datos[i].id;
var nombre = datos[i].nombre;
var jefe = datos[i].jefe;
alert(id);
drawChart(id, nombre);
function drawChart(id, nombre) {
//alert("Id: " + id + " | Nombre: " + nombre);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
data.addRows([
[nombre, jefe, id]
]);
var chart = new google.visualization.OrgChart(document.getElementById('contenido'));
chart.draw(data, {allowHtml:true});
}
}
},
error: function(error){
alert(error);
}
});
}
</script>
</head>
<body onLoad="json()">
<div id="contenido"></div>
</body>
JSON result:
[
{
"id":"1",
"nombre":"Andrey",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-G1-icon.png",
"jefe":""
},
{
"id":"2",
"nombre":"Enrique",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Andrey"
},
{
"id":"3",
"nombre":"Chero",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-E4-icon.png",
"jefe":"Andrey"
},
{
"id":"4",
"nombre":"Ricardo",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Chero"
},
{
"id":"5",
"nombre":"Jhon",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-H1-icon.png",
"jefe":"Enrique"
}
]
This displays like:
And, if i remove the alert(id) form the HTML code (in ajax), just shows the last object of the JSON:
How can i fix this?
or, is there any other option to do this chart?
Thank your for answers
The bellow code worked for me
index.html
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['orgchart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "ajax/organization.php",
success: function(result){
var result = JSON.parse(result);
if ((emp_count = result.length) > 0) {
console.log(result);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addRows(emp_count);
for (i = 0; i < emp_count; i++) {
data.setCell(i, 0, result[i].emp);
data.setCell(i, 1, result[i].manager);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
}
});
}
</script>
organization.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
$query=mysql_query("select emp, manager from employees") or die(mysql_error());
# Collect the results
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
Related
I'm trying to sort an XML feed alphabetically by "LastName" without creating an XSLT template, I have the below code, but it returns and error.
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "https://cors-anywhere.herokuapp.com/https://showcast.com.au/showcast/webservice/actors.aspx?agencyId=&Password=",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml){
$(xml).find("artist").each(function(){
var nx_name = $(this).find("FirstName").text() + ' ' + $(this).find("LastName").text();
var nx_pic = '';
$(this).find("Photos SmallPhotos Photo").each(function(){
if( $(this).find("IsDefault").text() == "True" ){
nx_pic = $(this).find("Url").text();
return false;
}
});
var nxlink = $(this).find("URLlink").text();
var nxhtml = '<div class="nxitem"><div class="nxwrap"><div class="nximgwrap"><img src="'+nx_pic+'"></div></div><br/><span class="nxname">'+nx_name+'</span></div>';
$("#nxdisplay").append(nxhtml);
});
}
</script>
Here is the output of my function sam() in HTML:
["2020-02-14", 324.7300, 325.9800, 322.8500, 324.9500, 20028447],
["2020-02-13", 324.1900, 326.2200, 323.3500, 324.8700, 23686892],
["2020-02-12", 321.4700, 327.2200, 321.4700, 327.2000, 28432573],
["2020-02-11", 323.6000, 323.9000, 318.7100, 319.6100, 23580780],
["2020-02-10", 314.1800, 321.5500, 313.8500, 321.5500, 27337215],
I am trying to get that very output of sam() to be read as an object in this line of code below.
"data": [
sam() ],
At the moment sam() in that location keeps outputting that above sequence of dates and price numbers. I need for sam() in that location to be read so that the above sequence would be integrated into the stock chart that I am working on. If I add all of that code as a non-string into the "data"[ ], it will print out the stock chart with the dates and prices, but when I simply use the function sam() in there, it doesn't print out the chart. It only does dates and numbers
Here is the entire code that uses the sam() function. When you execute it, it will output a sequence of dates and numbers. When you copy and paste that output into the line of code near the bottom labeled "data" : [ ], it will output a nice looking stock chart using the dates and numbers. I need a function that can do the same.
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script data-require="highstock#0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/highstock.js"></script>
<script data-require="highstock#0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<title>
How to get the array of dates between
two dates in JavaScript ?
</title>
</head>
<body style = "text-align:center;">
<div id="myData"></div>
<div id="demo"></div>
<div id="demo1"></div>
<script>var tday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var tmonth=["-01-","-02-","-03-","-04-","-05-","-06-","-07-","-08-","-09-","-10-","-11-","-12-"];
function GetClock(){
var d=new Date();
var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getFullYear();
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;
if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}
if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;
var clocktext=""+nyear +tmonth[nmonth] +ndate +"";
document.getElementById('clockbox').innerHTML= clocktext;
}
GetClock();
setInterval(GetClock,1000);</script>
<script>
function heavy(){
var today = new Date("2014-10-01"); //YYYY-MM-DD
var startDate = new Date("2014-10-01");
var endDate = new Date("2016-10-10" );
//YYYY-MM-DD
var getDateArray = function(start, end) {
var arr = new Array();
while (startDate < end) {
arr.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return arr.reverse().toLocaleString().replace(new RegExp('/', 'g'), '-').replace(new RegExp("8:", 'g'), '').replace(new RegExp("00", 'g'), '').replace(new RegExp("PM", 'g'), '').replace(new RegExp("AM", 'g'), '').replace(new RegExp(",", 'g'), '').replace(new RegExp(":", 'g'), '');
}
var dateArr = getDateArray(startDate, endDate);
// Output
for (var i = 0; i < dateArr.length; i++) {
document.write( dateArr[i] );
}
}
</script>
<script>
function heavy1(){
var cars = [["2020-02-13"], ["2020-02-12"]];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;}
</script>
<script>
function sam(){
fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
var arrw = ["2020-02-14",
"2020-02-13",
"2020-02-12",
"2020-02-11",
"2020-02-10",
"2020-02-07",
"2020-02-06",
"2020-02-05",
"2020-02-04",
"2020-02-03",
"2020-01-31",
"2020-01-30",
"2020-01-29",
"2020-01-28",
"2020-01-27",
"2020-01-24",
"2020-01-23",
"2020-01-22",
"2020-01-21",];
for (var i = 0; i < arrw.length; i++) {
var joe = '[' +"\""+ arrw[i]+ "\"" + "," + " " + data['Time Series (Daily)'][arrw[i]]['1. open']+"," + " " +data['Time Series (Daily)'][arrw[i]]['2. high']+"," + " " +data['Time Series (Daily)'][arrw[i]]['3. low']+","+ " " +data['Time Series (Daily)'][arrw[i]]['4. close']+","+ " " +data['Time Series (Daily)'][arrw[i]]['5. volume' ] + ']' + "," ;
document.write(joe);
}}}
</script>
<div id="container"></div>
<script>
var json = {
"dataset": {
"data": [
sam()
],
}
};
var hiJson = json.dataset.data.map(function(d) {
return [new Date(d[0]).getTime(), d[4]]
});
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: 'MS Stock Price'
},
series: [{
name: 'MS',
data: hiJson,
tooltip: {
valueDecimals: 2
}
}]
});
</script>
</body>
</html>
I am working on displaying weather info received from a weather station to display as live chart on my web page. I am using charts.js library to render weather data that's fetched from the weather station as JSON data.
In The code, function loadChart() fetched the json data about one field from weather station i.e. 'Humidity' and passes it (as int) to dspChrt(hum) to render the graph.
The main task to do in dspChrt(hum) method that renders the graph to put the data received from laodChrt() in an array that is updated each minute to use it as parameter to display live weather data as a line graph.
As the weather station updates data each minute, I am using setInterval(loadChart, 60000) method to fetch updated json data each minute.
I am following this tutorial that uses this method I am trying to implement.
[Chart.js] little update example
But it's not working though.
Here is my code:
<html>
<head>
<meta charset="utf-8">
<title>Weather Update</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
function dspChrt(hum[]) { // to be called by loadChart() to render live chart
var ctx = document.getElementById('myChart').getContext('2d');
var N = 10;
for(i=0; i<N; i++)
hum.push(0);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
label: 'Humidity',
data: hum, // json value received used in method
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Temprature',
data: [2, 29, 5, 5, 2, 3, 10],
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}
</script>
<script>
var myVar = setInterval(loadChart, 60000);
function loadChrt() { //fetches json data & calls dspChart() to render graph
var wData, hum;
var requestURL = 'https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s'; //URL of the JSON data
var request = new XMLHttpRequest({
mozSystem: true
}); // create http request
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
wData = JSON.parse(request.responseText);
hum = wData.humidity;
console.log("wData: " + wData);
console.log("hum: " + hum);
dspChrt(hum);
}
}
request.open('GET', requestURL);
request.send(); // send the request
//dspChrt(hum);
}
</script>
</head>
<body onload="loadChart();">
<div class="container">
<h2>Weather Update</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>
You have typo in the for function name loadChart.
The variable declarations and function definitions are needed to be added before being used.
Reduced the length of array to 7 instead of 10.
Here is updated code snippet. I've added the temperature as well. ;)
var humArray = [];
var temArray = [];
var N = 7;
for (i = 0; i < N; i++) {
humArray.push(0);
temArray.push(0);
}
function loadChart() { //fetches json data & calls dspChart() to render graph
var wData, hum, tem;
var requestURL = 'https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s'; //URL of the JSON data
var request = new XMLHttpRequest({
mozSystem: true
}); // create http request
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
wData = JSON.parse(request.responseText);
hum = wData.humidity;
tem = wData.temperature;
humArray.shift();
humArray.push(hum);
temArray.shift();
temArray.push(tem);
dspChrt(humArray, temArray);
}
}
request.open('GET', requestURL);
request.send(); // send the request
//dspChrt(hum);
}
var myVar = setInterval(loadChart, 60000);
function dspChrt(humArray, temArray) { // to be called by loadChart() to render live chart
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
label: 'Humidity',
data: humArray, // json value received used in method
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Temprature',
data: temArray,
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<body onload="loadChart();">
<div class="container">
<h2>Weather Update</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
Hope it helps.
i want to group this chart like " gender 1" is men and "gender 2" is women, but when i try to code the chart it's difficult to differentiate them.
here is my code
//data.php
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'dbintegrasi');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT JenisKelaminID, COUNT(JenisKelaminID) as jumlah FROM tahunmasukmagister GROUP BY JenisKelaminID");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row){
$data[] = $row;
}
//freee memory associated with result
$result->close();
//close connection
$mysqli->close();
//new print the data
print json_encode($data);
//app.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/chartjs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var Gender = [];
var jumlah = [];
for(var i in data){
Gender.push("Gender " + data[i].JenisKelaminID);
jumlah.push(data[i].jumlah);
}
var chartdata = {
labels: Gender,
datasets: [
{
label : 'Gender',
backgroundColor: 'rgba(250, 300, 100, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: jumlah
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
please help me to solve this, thankyou
In you app.js file on line number 10 :
Gender.push("Gender " + data[i].JenisKelaminID);
you can set an if condition instead of it Like
if(data[i].JenisKelaminID == 1){
Gender.push("Men");
} else if(data[i].JenisKelaminID == 2){
Gender.push("Women");
} else {
Gender.push("Other");
}
In there the chart name is defined, hope it will help your work.
I want to make a ganttchart, where I can retrieve data from database using mysql.
Highcharts do no include ganttchart, so i tried google charts. I am able to retrieve values from database and its can be seen in the page source, but not getting the output.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", {packages:["gantt"]});
google.setOnLoadCallback(drawChart);
<?php
$con = mysqli_connect("localhost","root","","db1") or die("could not connect");
$query= "select * from view_chart";
$qresult=mysqli_query($con,$query);
$results = array();
while($res = mysqli_fetch_array($qresult))
{
$results[] = $res;
}
$gan_data = array();
foreach($results as $result)
{
$gan_data[] = ($result['Brands']);
$gan_data1[] = ((int)$result['ratings']);
$gan_data2[] = ((int)$result['bigbazar']);
}
$gan_data = json_encode($gan_data);
$gan_data1 = json_encode($gan_data1);
$gan_data2 = json_encode($gan_data2);
mysqli_free_result($qresult);
?>
function drawChart() {
// var container = document.getElementById('gantt');
//var chart =new google.visualization.GanttChart(container);
alert('hello');
var data = new google.visualization.arrayToDataTable(<?=$gan_data?>);
data.addColumn( type: 'string', id: 'Brands' );
data.addColumn( type: 'number', id: 'ratings' );
data.addColumn( type: 'number', id: 'bigbazar' );
data.addRows([
<?php echo $gan_data; ?>,
<?php echo $gan_data1; ?>,
<?php echo $gan_data2; ?>]);
var options = {
height: 275
};
var chart = new google.visualization.GanttChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>