Creating c3 graphs with dynamic values - php

Below is the code I'm using to generate a line graph using c3.js. In the variable 'value' I'll get the values to be plotted as comma separated values. I've hard coded the values now. With this code, the graph generated has only one value - '0'.
This code doesn't work :
var name = "Graph Values";
var value = "120,150,120,120,120";
var obj = {
"data1": [value]
}
var chart = c3.generate({
bindto: '#chart1',
data: {
columns: [
[name].concat(obj.data1)
]
}
});
This code works :
var name = "Graph Values";
var value = "120,150,120,120,120";
var obj = {
"data1": [120,150,120,120,120]
}
var chart = c3.generate({
bindto: '#chart1',
data: {
columns: [
[name].concat(obj.data1)
]
}
});

The problem was the value you declared was not in the proper way Try this
var value = [120,150,120,120,120];
var obj = {
"data1": value
} ;

you can put your data in an array.
var Array=[]; //Store your dynamic values here
var chart = c3.generate({
bindto: '#chart1',
data: {
columns:[Array],
type : 'bar',
}
});

Related

foreach JSON array in jquery

I have an Array in the following format :
[["tag1","tag2","tag3","tag4","tag5","tag6","tag7","Thy","YUI"],["","",0,"jkghjg","hgjhg","kjhkjhg","kjghjkg)","gjhg","jkjkghj"]]
I need to "foreach" the array and get each values one by one like: Features , notes ...
When I put it into $.each() I am getting this error:
Uncaught TypeError: Cannot use 'in' operator to search for '1103' in ..
How do I get it?
did you mean make the array as associative JSON object?
try this
var a = [["Features", "Notes", "Code", "Value", "Testing", "BAC", "Total", "Thy", "YUI"],
["", "", 0, "jkghjg", "hgjhg", "kjhkjhg", "kjghjkg)", "gjhg", "jkjkghj"]]
var json = {}
for (var i in a[0]) {
var key = a[0][i];
var val = a[1][i];
json[key] = val;
}
console.log(json);
console.log(json.Testing);
var a_data= [["Features","Notes","Code","Value","Testing","BAC","Total","Thy","YUI"],["","",0,"jkghjg","hgjhg","kjhkjhg","kjghjkg)","gjhg","jkjkghj"]]
var output="";
$.each(a_data,function(index,data){
output+=data.join(",")
})
console.log(output)
try this
var a = [["Features", "Notes", "Code", "Value", "Testing", "BAC", "Total", "Thy", "YUI"], ["", "", 0, "jkghjg", "hgjhg", "kjhkjhg", "kjghjkg)", "gjhg", "jkjkghj"]]
$.each(a, function (i, data) {
$.each(data, function (j, val) {
console.log(val);
});
});
you can also try this if you want to use foreach method
Array.prototype.forEach.call(a,function(rm){
rm.map(function(ed){
console.log(ed)
})
})

GET key value from AJAX response

I'm making a cross domain call to a php which returns this:
response=2&count=15&id=84546379&firstname=adsa&emailstatus=
I want to pick out the values of response and id, but not sure how, my code is as follows:
**
xhr.request({
url: "../promo_getstate2.php",
method: "POST",
data: {
email: emailaddress,
country: country,
lang: lang,
source: '1312_XMAS_dly'
}
}, function(response){
getstate = response['response'];
regID = response['id'];
console.log(getstate)
console.log(regID)
})
but it's not geting those values. How do I do this?
The response is:
" response=2&count=15&id=84546379&firstname=adsa&emailstatus="
**
What you can do is create a params object of all parameters in the response as shown below:
function parseResponse(str) {
var arr = str.split("&");
var temp, params = [];
for(var i = 0; i < arr.length; ++i) {
temp = arr[i].split("=");
params[temp[0]] = temp[1];
}
return params;
}
var values = parseResponse("response=2&count=15&id=84546379&firstname=adsa&emailstatus=")
You can then access values as:
values['response']; // 2
values['id']; // 84546379
Code as that:
<Script language="javascript">
var vars=GetRequest("response=2&count=15&id=84546379&firstname=adsa&emailstatus=");
document.write(JSON.stringify(vars));
function GetRequest(v) {
var url = "?"+v;//location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
</script>
Then you can get the values. For example, the json of the result is
{"response":"2","count":"15","id":"84546379","firstname":"adsa","emailstatus":""}

flot chart with json data is empty

I need to plot chart in flot with data returned by a php script as json encoded data
i get the data in through jquery like this
$("button").click(function(){
var dp1 = $('#dp1').val();
var dp2 = $('#dp2').val();
$.ajax({
type: "GET",
url: "chart.php",
datatype:"json",
success: onSuccess,
data: {d1:dp1, d2:dp1}
});
function onSuccess(series) {
var plotarea = $("#pieChart");
plotarea.css("height", "300px");
plotarea.css("width", "400px");
$.plot( plotarea , [
{
data: series,
bars: {
show: true
}
}
] );
}
});
the data return is json encoded i can see it in firebug like so
[["ebbok1",39.55],["ebbok2",92.23],["ebbok3",102.44]]
but my chart is empty
the php file returning the json data is
$dataset = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//echo $row['amount'] . "\t" . $row['product_name']. "\n";
$dataset[] = array( $row['product_name'], $row['amount'] );
}
echo json_encode($dataset,JSON_NUMERIC_CHECK);
what am i doing wrong?
EDIT
i modified my php script, it now returns data like this
[{"label":"ebook1","data":39.55},{"label":"ebook2","data":92.23},{"label":"ebook3","data":102.44}]
but i still get empty chart
Your $.plot call doesn't look correct. You are mixing the options and data together.
var series = [
{"label":"ebbok1","data":12},
{"label":"ebook1","data":27.55},
{"label":"ebook2","data":92.33},
{"label":"ebook3","data":102.44}
];
$.plot( $("#somePlot") , series,
{
series: {
pie: {
show: true
}
}
}
);
See fiddle here.
You've misunderstood how a set of data is expected for flot.
You have:
series = [["label",1],["label2",2],... ];
Flot expects data formatted like this:
series = [[[x1,y1],[x2,y2],...]];// where xN and yN are all NUMBERS
See also the documentation on this topic.
So assuming that you really want to see the labels you've specified, one way to deal with that is to use the ticks property of the xaxis. So you'd return two sets of data:
data = [[[0,1],[1,1],...]];
tickLabels = [[0,"label1"],[1,"label2"],...];
Then in your flot options specify this:
$.plot( plotarea , data, {
series: {
bars: {
show:true;
}
},
xaxis: {
ticks:tickLabels
}
} );
Example: http://jsfiddle.net/ryleyb/8gGEz/1/
EDIT: If you want to keep returning your series data the same way, you can do the manipulation in the javascript:
var tickLabels = [];
for (var i =0;i<series.length;i++){
tickLabels.push([i,series[i][0]);
series[i][0] = i;
}
var data = [series];
//now you can call flot as I described above.
I meet the same problem with you. But now I figure it out.
The problem is cause by your data
[["ebbok1",39.55],["ebbok2",92.23],["ebbok3",102.44]]
It look like what you want to show at x-axis is "category" type.
So flot(v0.8.2) provide 'categories' mode to present the x-axis show what you want as categories.
As following:
Step1: add categories module to your HTML
<script type="text/javascript" src="flot/jquery.flot.categories.js"></script>
Step2: add the following to your js.
var options={
xaxis:{mode: "categories"}
};
try it and enjoy it :)

Parse json data into variables and submit to a function on each iteration

I created a php script that generates the json response
this is the example of the output:
[[],{"idgps_unit":"2","lat":"40","lon":"40","name":"ML350","notes":"Andrew","dt":"2012-10-29 19:43:09","serial":"3602152","speed":"44","odometer":"208.49"},{"idgps_unit":"1","lat":"42","lon":"39","name":"unit1","notes":"fake unit 1","dt":"2012-10-18 18:16:37","serial":"12345","speed":"0","odometer":"0.16"}]
This is how I form the response in PHP:
$data[] = array();
foreach ($list->arrayList as $key => $value) {
$unit = new Unit();
$unit = $value;
//create array for json output
$data[] = array('idgps_unit' => $unit->idgps_unit, 'lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes,
'dt' => $unit->dt, 'serial' => $unit->serial, 'speed' => $unit->speed,
'odometer' => $unit->odometer);
}
echo json_encode($data);
Now, in JS I did this:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
success : function(data) {
var jsonData = JSON.parse(data);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: START
var C_longitude = 0;
var C_name = 0;
var C_idgps_unit = 0;
var C_serial = 0;
var C_speed= 0;
var C_notes= 0;
var C_dt = 0;
var C_time = 0;
var C_odometer = 0;
initialize(C_longitude,C_name,C_idgps_unit, C_serial,C_speed, C_notes, C_dt, C_time, C_odometer);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: END
}
});
});
}
I need to parse the json reponce into values
Assuming that JSON.parse(data) only gets the associative array in the JSON response, you should be able to get the values in the JSON data like so:
var i = 1;
var C_longitude = jsonData[i]["lon"];
var C_name = jsonData[i]["name"];
Assuming that the first empty array is not removed by JSON.parse(), i = 1 would get the first batch of data and i = 2 would get the second.
The parsed JSON behaves the same way as if it was defined in JavaScript
If you put dataType: "json" in the ajax settings it will return you a json object than you don't need to parse it again. So this would look like:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
dataType: "json"
success : function(data) {
}
});
});
}
However you could also use your own option but than just use the parseJSON function so var jsonData = jQuery.parseJSON(data);

PHP JSON Highcharts load database result

I'm stuck!
I need to create highchart with json result. I found some sources here but can't put this to work.
The closest I can get was doing this:
Chart options:
var options = {
chart: {
renderTo: 'tudo',
defaultSeriesType: 'column',
rightMargin: 80
},
title: {
text: 'Weekdays'
},
subtitle: {
text: 'Source: somewhere in a calendar'
},
xAxis: {
labels: {
enabled: false
}
},
yAxis: [
{
min: 0,
title: {
text: 'Amount'
}
},
{
linkedTo: 0,
opposite: true
}
],
series: []
};
ajax call:
$.getJSON('ajax/calc.ajax.php', function(data) {
var series = [];
$.each(data, function(key, value) {
series.name = key;
series.data = value;
options.series.push(name);
});
var chart = new Highcharts.Chart(options);
});
highchart loads ok, and fills the series with Series 1, Series 2 ....
but no graphic is made, he keeps blank. ( something like this: Demo).
wanna know if I'm missing something or everything.
Thanks
update: i change the sql, now i'm working with 2 fields, and with this, the grafic work perfect, now i just want to know if doing like this its ok.
header('Content-Type: application/json');
while(!$res->EOF){
//$json = array("group" => "Web", "action" => "list");
$json[$res->fields["DESMAR"]] = array(intval($res->fields["QTD"]));
//$json["users"] = array(array("name" => "JulioGreff", "status" => "online"));
$res->MoveNext();
}
echo json_encode($json);
In your ajax call -
$.getJSON('ajax/calc.ajax.php', function(data) {
var series = []; // <---------------------- must be object not array
$.each(data, function(key, value) {
series.name = key;
series.data = value;
options.series.push(name); // <-------- it should be series not name
});
var chart = new Highcharts.Chart(options);
});
So, it would be as follows -
$.getJSON('ajax/calc.ajax.php', function(data) {
$.each(data, function(key, value) {
var series = {}; // <-------------------- moved and changed to object
series.name = key;
series.data = value;
options.series.push(series); // <-------- pushing series object
});
var chart = new Highcharts.Chart(options);
});
Also, considering the JSON you are receiving -
{"nome":"TRANSFORMADOR 250VA 0-230-380V / 0,24V-0-48V","modelo":"TRANSFORMADOR","marca":"SEIT","valor":"318.87|542.08","qtdade":"0"??}
what you are doing in the $.each -
series.data = value;
does not make sense.
series.data is an array. So, it could look like either as follows -
[y1, y2, y3, ....] // array of numbers (which are y values)
or as follows -
[[x1, y1], [x2, y2], [x3, y3], ....] // array of arrays of pair of numbers (x and y values)
or as follows -
// array of objects which can have x and y values as properties
[{
name: 'Point 1',
color: '#00FF00',
y: 0
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
So, make sure that your PHP code produces a JSON that matches an array of one of the above, then series.data = value inside your $.each will work.
Update:
Sorry, I do Java and have never done PHP so can't help you much with PHP. But, can you try with the following as your PHP, just to see if the chart shows up?
header('Content-Type: application/json');
$return_data = array(
array(array(10, 20), array(20, 30), array(56, 30), array(50, 20)),
array(array(10, 0), array(20, 10), array(56, 100), array(50, 40))
);
echo json_encode($return_data);
Update: To render pie while keeping the same PHP.
$.getJSON('ajax/calc.ajax.php', function(data) {
var series = { // <-------------------- create just one series object
type: 'pie',
data: [] //data array for new series
};
$.each(data, function(key, value) {
series.data.push([key, value[0]]);
});
options.series.push(series); // <-------- pushing series object
var chart = new Highcharts.Chart(options);
});
This should draw pie chart.
It looks like the problem lies in your PHP code. Highcharts expects a series to follow a particular format. In your case, things work out (partly) because name is one of the field it is looking for. The data, however, needs to be in one of three formats:
An array of y values (e.g. [0, 1, 2])
An array of arrays (x, y values; e.g. [[0,0], [1,1], [2,2]])
An array of objects meeting using point properties
You would want the last format, I think. For example:
var series = [];
series.name = "series1";
series.data = {y: 10}; //very minimalistic example of the object format
options.series.push(name);
To get your code to work, you might need to change the inside of your $.each function to something like this:
$.each(data, function(key, value) {
series.name = key;
series.data = {
y: value.property_you_are_interested_in
};
options.series.push(name);
});
...of course, if you wanted to use one of the other forms, it would be pretty easy as well:
//First form (array of y values)
var series = {};
series.data = [];
$.each(data, function(key, value) {
series.name = key;
series.data.push(value.property_you_are_interested_in);
});
options.series.push(series);
//Second form (array of x, y values)
var series = {};
series.data = [];
$.each(data, function(key, value) {
series.name = key;
series.data.push([value.X_property_you_are_interested_in, value.Y_property_you_are_interested_in]);
});
options.series.push(series);

Categories