Adding Data to amcharts chart from external json code - javascript

I've got a chart that needs to be manipulated with data from the database. Therefore I have converted the data from the database to JSON string. the problem is that I don't know how to integrate the JSON data I received right into the chart.
These are the files needed to make this work:
The php & PDO query:
<?php
/*host = 'localhost' Namecheap default. Could also use 127.0.0.1 */
try {
$connection= new PDO('mysql:host=localhost;dbname=clicrckc_andfit','clicrckc_osherdo','3563077');
$connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql="SELECT answer_vegitable,answer_cigarettes,answer_workout FROM answers where user_id=58";
$row=$connection->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
$main = array('data'=>$result,'value'=>array("bgcolor"=>"#f1fff1","message"=>"All records displayed"));
echo json_encode($main);
$connection = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
The HTML & JS needed for chart creation and manipluation:
<title>Statistics Chart</title>
<script src="../amcharts_3.13.1.free/amcharts/amcharts.js" type="text/javascript"></script>
<script src="../amcharts_3.13.1.free/amcharts/serial.js" type="text/javascript"></script>
<script type="text/javascript">
AmCharts.loadJSON = function("barClustered.php") {
// create the request
if (window.XMLHttpRequest) { // XMLHttpRequest object is the keystone of AJAX, and it is used to exchange small
//amounts of data with the server.
// IE7+, Firefox, Chrome, Opera, Safari (modern browsers).
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load it
// the last "false" parameter ensures that our code will wait before the
// data is loaded
request.open('GET',"barClustered.php", false); //Type of request,The acutal URL, asynchronously or not?
request.send(); // Send request to the server.
// Adding code after the send method in case of synchronous request (like the one above).
// parse and return the output
return eval(request.responseText); // responseText is getting the response data as a string.
};
</script>
<!-- The chart code -->
<script>
var chart;
var chartData = [
{
"questions": "Vegtables Eaten",
"This Week": 30.1,
"Last Week": 23.9,
"2 Weeks Ago": 27.5
},
{
"questions": "Workout (Minutes)",
"This Week": 29.5,
"Last Week": 25.1,
"2 Weeks Ago": 26.4
},
{
"questions": "Cigarettes smoked",
"This Week": 24.6,
"Last Week": 25,
"2 Weeks Ago": 28
}
];
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "questions";
chart.startDuration = 1;
chart.plotAreaBorderColor = "#DADADA";
chart.plotAreaBorderAlpha = 1;
// this single line makes the chart a bar chart
chart.rotate = true;
// AXES
// Category
var categoryAxis = chart.categoryAxis;
categoryAxis.gridPosition = "start";
categoryAxis.gridAlpha = 0.1;
categoryAxis.axisAlpha = 0;
// Value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisAlpha = 0;
valueAxis.gridAlpha = 0.1;
valueAxis.position = "top";
chart.addValueAxis(valueAxis);
// GRAPHS
// first graph
var graph1 = new AmCharts.AmGraph();
graph1.type = "column";
graph1.title = "This Week";
graph1.valueField = "This Week";
graph1.balloonText = "This Week:[[value]]";
graph1.lineAlpha = 0;
graph1.fillColors = "#ADD981";
graph1.fillAlphas = 1;
chart.addGraph(graph1);
// second graph
var graph2 = new AmCharts.AmGraph();
graph2.type = "column";
graph2.title = "Last Week";
graph2.valueField = "Last Week";
graph2.balloonText = "Last Week:[[value]]";
graph2.lineAlpha = 0;
graph2.fillColors = "#81acd9";
graph2.fillAlphas = 1;
chart.addGraph(graph2);
// Third graph
var graph3 = new AmCharts.AmGraph();
graph3.type = "column";
graph3.title = "2 Weeks Ago";
graph3.valueField = "2 Weeks Ago";
graph3.balloonText = "2 Weeks Ago:[[value]]";
graph3.lineAlpha = 0;
graph3.fillColors = "#9972C1";
graph3.fillAlphas = 1;
chart.addGraph(graph3);
// LEGEND
var legend = new AmCharts.AmLegend();
chart.addLegend(legend);
chart.creditsPosition = "top-right";
// WRITE
chart.write("chartdiv");
});
</script>
<script src="http://www.click-and-fit.me/amcharts_3.13.1.free/amcharts/serial.js"></script>
<script src="http://click-and-fit.me/amcharts_3.13.1.free/amcharts/amcharts.js"></script>
<body>
<div id="chartdiv" style="width:500px; height:600px;"></div>
</body>
These are the 2 files above in action:
http://click-and-fit.me/barClustered.php
Statistics Chart
Here's a screenshot of the 3 rows from the database I would like to show in the chart:
http://www.codingforums.com/redirect-to/?redirect=http%3A%2F%2Fimgbox.com%2FHfD1PuTQ
Currently the chart is filled with manually inputted data in a JSON format. How do I get the JSON string from the php file to be manipluated within the cart data? tried to look all over amcharts documentation and could not still understand how to do it.
Thanks in advance!

Try the following:
Change
AmCharts.loadJSON = function("barClustered.php") {
if (window.XMLHttpRequest) {
var request = new XMLHttpRequest();
} else {
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', "barClustered.php", false);
request.send();
return eval(request.responseText);
};
to
AmCharts.loadJSON = function(url) {
if (window.XMLHttpRequest) {
var request = new XMLHttpRequest();
} else {
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', url, false);
request.send();
return eval(request.responseText);
};
Change
chart.dataProvider = chartData;
to
chart.dataProvider = AmCharts.loadJSON('http://click-and-fit.me/barClustered.php');

Related

using the same javascript file but load different data each time during an AJAX call

I've got a javascript array with multiple variables....
I am looping through this array
during each loop, I am calling function print_tag
Below is the first function
function print_tags(all_tags,quantity_to_print) {
var print_array = all_tags.split(',');
let i = 0;
do {
print_tag(print_array[i],quantity_to_print,i);
i++;
} while (i < print_array.length);
}
All this is doing is taking the array and looping through each array entry and running another function that contains the AJAX.
function print_tag(tag,quantity_to_print,v) {
setTimeout(function() {
$.ajax({
type: "POST",
ajaxI: v,
url: "<?php echo http() . $websitedomain .'/Manage/js/DYMO/print_barcode.php'; ?>",
data: { "inv_id": tag, "lcount": quantity_to_print },
dataType: 'html',
success: function(data){
$('#resultDiv_' + tag).html(data);
console.log(tag);
}
});
}, 15000 * v);
}
All of this is to point out that the page the AJAX function is calling is using a SINGLE javascript file. It is a file that prints labels out on a DYMO label printer. Under normal scenerios, this works fine because I am sending 1 label to be printed each time; however, I'm now running a page that needs to send multiple (sometimes up to 24) different tags that need to be printed. Each tag is sent through an individual AJAX request. The PHP page is loading the correct data because I can see the output both in HTML and also in the console; however, the javascript file is printing the same tag each time. The javascript file isnt refreshing to the new tag information. I'm not sure if the javascript file is not being reloaded, or if it is somehow retaining information. Below is the javascript file....
My first thought is maybe the javascript file isnt "closing" and just being recalled which prints another of the previous tags. But I'm not a javascript expert so that may be crazy talk. But each time the javascript file loads, I need it to input NEW data and not the exact same data from the first tag.
//----------------------------------------------------------------------------
//
// $Id: TextMarkup.js 38773 2015-09-17 11:45:41Z nmikalko $
//
// Project -------------------------------------------------------------------
//
// DYMO Label Framework
//
// Content -------------------------------------------------------------------
//
// DYMO Label Framework JavaScript Library Samples: Text Markup
//
//----------------------------------------------------------------------------
//
// Copyright (c), 2011, Sanford, L.P. All Rights Reserved.
//
//----------------------------------------------------------------------------
(function()
{
// stores loaded label info
var label;
function escapeXml(xmlStr)
{
var result = xmlStr;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]];
for(var i = 0; i < findReplace.length; ++i)
result = result.replace(findReplace[i][0], findReplace[i][1]);
return result;
}
// addition
function repeat(func, times) {
func();
--times && repeat(func, times);
}
// called when the document completly loaded
function onload()
{
var textMarkupInput = document.getElementById('textMarkupInput');
//var printTextMarkupButton = document.getElementById('printTextMarkupButton');
var split = textMarkupInput.value.split(' | ');
//var printersSelect = document.getElementById('printersSelect');
//var printer = 'DYMO LabelWriter 450 Twin Turbo';
//var printer = 'DYMO LabelWriter 4XL';
var printer = split[0];
//var textInput = document.getElementById('textInput');
//var printButton = document.getElementById('printButton');
// loads all supported printers into a combo box
function loadPrinters()
{
var printers = dymo.label.framework.getPrinters();
if (printers.length === 0)
{
alert("No DYMO printers are installed. Install DYMO printers.");
return;
}
/* for (var i = 0; i < printers.length; i++)
{
var printer = printers[i];
if (printer.printerType == "LabelWriterPrinter")
{
var printerName = printer.name;
var option = document.createElement('option');
option.value = printerName;
option.appendChild(document.createTextNode(printerName));
printersSelect.appendChild(option);
}
}*/
}
//printTextMarkupButton.onclick = function()
$( document ).ready(function()
{
try
{
if (!label)
{
alert("Load label before printing");
return;
}
// set data using LabelSet and text markup
var labelSet = new dymo.label.framework.LabelSetBuilder();
var record = labelSet.addRecord();
var SKU = '';
var DESCRIPTION = '';
var BARCODE = '';
var NETWEIGHT = '';
var GROSSWEIGHT = '';
SKU += '<b>';
SKU += split[3];
SKU += '</b>';
DESCRIPTION += '<b>Description</b><br />';
DESCRIPTION += split[4];
BARCODE += split[5];
console.log(split[5]);
NETWEIGHT += '<b>';
NETWEIGHT += split[6];
NETWEIGHT += '</b>';
GROSSWEIGHT += '<b>';
GROSSWEIGHT += split[7];
GROSSWEIGHT += '</b>';
record.setTextMarkup('SKU', SKU);
record.setTextMarkup('DESCRIPTION', DESCRIPTION);
record.setTextMarkup('BARCODE', BARCODE);
record.setTextMarkup('NETWEIGHT', NETWEIGHT);
record.setTextMarkup('GROSSWEIGHT', GROSSWEIGHT);
repeat(function () {
//regular code
//setlabel(labelSetBuilder);
//var params = dymo.label.framework.createLabelWriterPrintParamsXml({twinTurboRoll: dymo.label.framework.TwinTurboRoll.Right});
var params = dymo.label.framework.createLabelWriterPrintParamsXml({twinTurboRoll: split[1]});
//var params = '';
//label.print(printersSelect.value, params, labelSet.toString());
label.print(printer, params, labelSet.toString());
// addition
}, lcount);
}
catch(e)
{
alert(e.message || e);
}
});
function getAddressLabelXml() {
function loadXMLDoc(theURL)
{
if (window. XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari, SeaMonkey
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theURL +'?_=' + new Date().getTime(), false);
xmlhttp.send();
}
var xmlhttp=false;
//loadXMLDoc('https://www.americanstrapping.com/Manage/js/DYMO/STEEL_STRAPPING_LARGE_LABEL.label');
loadXMLDoc(split[2] +'.label');
if(xmlhttp==false){ alert('NOPE'); }
else { return xmlhttp.responseText; }
}
function loadLabelFromWeb()
{
// use jQuery API to load label
// $.get("Address.label", function(labelXml)
// {
label = dymo.label.framework.openLabelXml(getAddressLabelXml());
// }, "text");
}
loadLabelFromWeb();
// load printers list on startup
loadPrinters();
};
function initTests()
{
if(dymo.label.framework.init)
{
//dymo.label.framework.trace = true;
dymo.label.framework.init(onload);
} else {
onload;
}
}
window.onload = initTests();
} ());
BELOW IS THE DATA BEING SENT TO LAST JAVASCRIPT CODE...YOU CAN SEE THAT THE BARCODES ARE DIFFERENT....
DYMO LabelWriter 450 Twin Turbo | Left |
https://www.......com/Manage/js/DYMO/STEEL_STRAPPING_SMALL_LABEL
| HSE-HT24114-TEST-NCW | 1-1/4" X .024 HSE-HT TEST MATERIAL |
TEST-126725 | 600 | 645
DYMO LabelWriter 450 Twin Turbo | Left |
https://www......com/Manage/js/DYMO/STEEL_STRAPPING_SMALL_LABEL
| HSE-HT24114-TEST-NCW | 1-1/4" X .024 HSE-HT TEST MATERIAL |
TEST-795061 | 600 | 645
But no matter how many times I loop through, Label 1 prints every single time. It never goes to the other data.

How to open relative information onClick on dynamically created child

I am creating timers for workers. A user can add worker with some time. After that it will create a countdown timer for that worker. Start time and target time is saved on database so i am starting timer according to that. And the timer is worked fine. Now i want that if i click on any of the created child it should i want to call my php with POST id of the Work which is added on child creation and then open detailed information of the work which was filled when worker was added. So basically i want help in post WorkID of the selected child on click and call my php script.
On Page load i am getting data like this
function GetMachineSinger() {
var http = new XMLHttpRequest();
var url = 'php/StitchTimerSinger.php';
http.open('GET', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
for(var i=0;i<jsonResponse.length;i++){
var index = jsonResponse[i];
var empname = index["EmployeeName"];
var hour = index["Hour"];
var minute = index["Min"];
var second = index["Sec"];
var available = index["Available"];
var id = index["WorkID"];
if(available<50){
addEmployee(id,empname,hour,minute,second);
}
document.getElementById("avlmc").innerHTML = available;
}
}
}
http.send();
}
addEmployee()
function addEmployee(id,emp,hr,mi,sec)
{
var employee = new Employee(id,emp,hr,mi,sec);
display.appendChild(employee.domObj);
employee.startTimer();
}
class Employee
{
constructor(id,name,hr,min,sec)
{
var self=this;
this.timer;
this.timeInSec;
this.domObj=document.createElement("div");
this.timeSpan=document.createElement("span");
this.domObj.style.backgroundColor = '#4CA';
this.domObj.style.border = 'none';
this.domObj.style.height = '100px';
this.domObj.style.width = '100px';
this.domObj.style.color = 'white';
this.domObj.style.padding = '20px';
this.domObj.style.textAlign = 'center';
this.domObj.style.textDecoration = 'none';
this.domObj.style.display = 'inline-block';
this.domObj.style.fontSize = '26px';
this.domObj.style.borderRadius = '50%';
this.domObj.style.margin = '20px';
this.domObj.style.justifyContent = "center";
this.timeInSec=hr*60*60+min*60+parseInt(sec);
this.timeSpan.innerHTML=hr+":"+min+":"+sec;
this.domObj.innerHTML=name+"<br>";
this.domObj.appendChild(this.timeSpan);
// console.log("0:"+this.timeInSec);
}
startTimer()
{
this.timer=setInterval(this.updateTime.bind(this),1000);
}
updateTime()
{
var hr,min,sec,temp;
if (this.timeInSec<=0)
{
clearInterval(this.timer);
}
else
{
this.timeInSec--;
//console.log("1:"+this.timeInSec);
sec=this.timeInSec % 60;
temp=this.timeInSec-sec;
temp/=60;
//console.log("2:"+temp);
min=temp % 60;
temp-=min;
hr=temp/60;
this.timeSpan.innerHTML=hr+":"+min+":"+sec;
if (min<10 && hr<1){
this.domObj.style.backgroundColor = '#ef5350';
}
}
}
}
Try
this.domObj.addEventListener('click', function (event) {
// do something
//for opening new window
let w = window.open('about:blank','name','height=200,width=150');
// w.document.open()
w.document.write('any HTML');
w.document.close();
});

update function on ajaxObject

When a button is clicked on the webpage a table of data is displayed. I want to scrape that data but I can't find where it comes from in the website source code.
This is the tag for the button:
<button type="submit" onclick="divChangeStateOn('load-raw-0062294377Amazon.com'); getRaw('0062294377', 'Amazon.com', 'lr-0062294377Amazon.com',this);"style="margin-bottom: 4px; width: 120px; text-align: left;" name="load-raw"><img src='images/workstation.png'/> raw data</button>
I believe that the getRaw function is where the data comes from (I'm not positive about this) so I looked at the javascript code for the getRaw function
function getRaw(asin, store, res, caller)
{ document.getElementById(res).innerHTML = '<p align="center" valign="top"><img align="center" src="phpmy_loading.gif"></p>';
var poststr = "raw=" + encodeURI(asin) +
"&site=" + encodeURI(store);
var updateResults = new ajaxObject(res, 'extra.php', caller);
updateResults.update(poststr);
}
I have been having a hard time finding any documentation about ajaxObject and can't find any information about the update function. What is ajaxObject.update doing and is it possible for me to access the data that appears when the button is clicked?
function divChangeStateOn(divID)
{ var divElem = document.getElementById(divID);
divElem.style.display = 'block';
}
EDIT: The link to the source code view-source:http://www.ranktracer.com/account_workstation.php it might be password protected but I was just using the demo version
EDIT 2:
I am basically trying to write a script that replicates the Ajax http request. This where I am at, it doesn't work and I am especially concerned about where data = uri
x = time.time()
print x
timestamp = datetime.fromtimestamp(x/1000.0)
print timestamp
uri = "raw=0062294377&site=Amazon.com&timestamp="+str(timestamp);
url = "lr-0062294377Amazon.com"
length = str(len(uri))
headers = {'X-Requested-With': 'XMLHttpRequest',
"Content-type": "application/x-www-form-urlencoded",
"Content-length": length,
"Connection" : "close"}
s = Session()
r = s.post(url= url, data= uri, headers= headers)
The entire code for ajaxObject is present in the link you provided. Please let us know what help you are expecting here?
function ajaxObject(layer, url, caller) {
if (caller) {
disableButton(caller, 'disable');
}
var that = this;
var updating = false;
this.callback = function() {}
var LayerID = document.getElementById(layer);
this.update = function(passData) {
if (updating == true) {
return false;
}
updating = true;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX == null) {
alert("Your browser doesn't support AJAX.");
return false
} else {
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4 || AJAX.readyState == "complete") {
if (caller) {
disableButton(caller, 'enable');
}
LayerID.innerHTML = AJAX.responseText;
delete AJAX;
updating = false;
that.callback();
}
}
var timestamp = new Date();
var uri = passData + '&timestamp=' + (timestamp * 1);
AJAX.open("POST", url, true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", uri.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.send(uri);
return true;
}
}
}

Dynamic Guides for amCharts

I can add guides (vertical lines) to my amchart this way:
var guide1 = new AmCharts.Guide();
guide1.date = new Date(2014, 5, 27);
guide1.lineColor = "#CC0000";
guide1.lineAlpha = 1;
guide1.dashLength = 2;
guide1.inside = true;
guide1.labelRotation = 90;
guide1.label = "Guide label";
stockPanel.categoryAxis.addGuide(guide1);
How could I add a number of these guides dynamically from a list of dates in a database?
Would I be able to generate each one with PHP and include them in my script?
Sample PHP (echoGuide.php):
<?php
$js = <<<JS
var guide1 = new AmCharts.Guide();
guide1.date = new Date(2014, 5, 27);
guide1.lineColor = "#CC0000";
guide1.lineAlpha = 1;
guide1.dashLength = 2;
guide1.inside = true;
guide1.labelRotation = 90;
guide1.label = "Guide label";
JS;
header("Content-type: text/javascript");
echo $js;
exit();
?>
Sample JS in HTML file:
var guide = AmCharts.loadJSON('echoGuide.php');
stockPanel.categoryAxis.addGuide(guide);
AmCharts.loadJSON:
AmCharts.loadJSON = function(url) {
// create the request
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load it
// the last "false" parameter ensures that our code will wait before the
// data is loaded
request.open('GET', url, false);
request.send();
// parse and return the output
return eval(request.responseText);
};
Found a solution:
gDates = AmCharts.loadJSON('db/fetchgDates.php');
for (var key_2 in gDates) {
var obj_2 = gDates[key_2];
var date_2_temp = new Date(obj_2['date']);
var guide = new AmCharts.Guide();
guide.date = date_2_temp;
guide.lineColor = "#CC0000";
guide.lineAlpha = 1;
guide.dashLength = 2;
guide.inside = true;
guide.labelRotation = 90;
guide.label = "test";
stockPanel.categoryAxis.addGuide(guide);
}

some confusion over calling drawchart in google chart on click of a button

I am trying to generate column chart on click of a button.When I click on the button drawchart() is called but no chart is created on screen.I examined the function by using alerts and found that data.addRow(array1[i],array2[j]) doesnt execute.The both arrays contain values extracted from json
Also when I remove this button and call function drawChart() on page load,I can see that only chart is created but no columns are drawn to it as there are no values in both the arrays.Any kind of help is really appreciated.
My code
<script type="application/javascript">
function loadJSON()
{
alert("hello");
alert(category);
alert(subcat);
alert(subdem);
var data_file = "https://tc.api.tibco.com:43/TopOne/v1/"+category+"/"+subcat+"/"+subdem;
alert("abc")
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
alert("in try");
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{ alert("in try1");
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{ alert("in try2");
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if(http_request.readyState ==1){ alert("1");}
if(http_request.readyState ==2){ alert("2");}
if(http_request.readyState ==3){ alert("3");}
if(http_request.readyState ==4){ alert("4");}
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
alert(http_request.responseText);
alert(jsonObj);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
//alert( jsonObj.Category.CategoryName);
//alert(jsonObj.Category.CategoryName.Demographies.DemographyName);
//document.getElementById("Country").innerHTML = jsonObj.country;
alert(jsonObj.Category[0].SubCategory[0].Demographies[0].Items[0].Name);
alert(jsonObj.Category[0].SubCategory[0].Demographies[0].Items[1].Name);
for(i = 0;i<10;i++)
{
array1[i] = jsonObj.Category[0].SubCategory[0].Demographies[0].Items[i].Name;
array2[i] = jsonObj.Category[0].SubCategory[0].Demographies[0].Items[i].SalesCount;
}
for(i=0;i<10;i++)
{
alert(array1[i]+" "+array2[i]);
}
}
}
http_request.open("GET", data_file, true);
http_request.setRequestHeader("accept","application/json");
http_request.send();
}
function drawChart(){
alert("hello");
var data = new google.visualization.DataTable();
data.addColumn('string', 'name');
data.addColumn('number', 'salescount');
alert("ggg");
for(i = 0; i < array1.length; i++)
data.addRow([array1[i], array2[i]]);
var options = {
title: "Movies",
width: 600,height:400
//hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('lowerRightDiv'));
chart.draw(data, options);
}
function initialize(){
$("button.charts").click(function() {
drawChart();
});
}
google.setOnLoadCallback(initialize);
google.load("visualization", "1", {packages:["corechart"]});
</script>
My code for the created button are
<button class="charts" onclick="initialize();"style="left:400px;">Generate charts</button>

Categories