I am using laravel 5.1 PHP framework and a sign chart from a javascript, But when i send data from controller with ' (single quote) but JavaScript Parse as some undefined value
$data_B_Temp = "{x : new Date('".$piecesTime[$dataLength]."'), y :".$pieces[$dataLength]."}";
this variable will make a graph point input
as
$(function () {
var chart = new CanvasJS.Chart("TempChart",
{
axisX:{
title: "time",
gridThickness: 2,
interval:1,
intervalType: "hour",
valueFormatString: "hh TT K",
labelAngle: -10
},
axisY:{
title: "distance"
},
data: [
{
type: "line",
dataPoints:[{{$data_B_Temp }}]
}
]
});
$("#TempChart").CanvasJSChart(chart.render());
});
But the javascript executes as :
dataPoints:[{x : new Date('2015-10-30 18:16:08'), y :38.5}]
I'm confused ' is coming? how to solve it?
According to the Laravel Blade documentation, using {{ }} results in an escaped string, which would cause the behavior that you're seeing.
Try using {!! !!} instead; using that syntax will tell Blade to not escape the string.
...
dataPoints: [{!! $data_B_Temp !!}]
...
Related
I am trying to create a grouped bar chart using Observable's Plot.plot in JavaScript (code is in TypeScript).
The problem is that the x-axis is showing each specific date, however I want the dates to show dynamic months or weeks, not specific dates.
This is the code:
const chart = Plot.plot({
x: { axis: null, domain: ["Add", "Remove"], },
y: { tickFormat: "s", label: "↑ Access Requests", grid: true },
color: {
legend: true,
type: "categorical",
domain: ["Add", "Remove"],
range: redGreenColorRange,
},
style: {
background: "transparent",
},
width: 1350,
caption: "in 2 week increments",
facet: {
data: groupedAddRemove,
label: "Created Date",
x: "createdDate",
// thresholds: d3.utcWeeks,
// ^ this doesn't work, but a similar structure has worked in other projects I've seen
},
marks: [
Plot.barY(groupedAddRemove, {
x: "type",
y: "count",
fill: "type",
}),
Plot.ruleY([0]),
],
});
and this is what it looks like:
I want the x-axis marks to show a dynamic version of Months, like:
My data structure either could show the "Date" as a string, or a TypeScript typeof Date object
data structure with date with a type of string
data structure with date with a type of Date
This is the data structure type:
The 'groupedAddRemove' is an array of this type
( AddRemoveBarChartType[] )
type AddRemoveBarChartType = {
createdDate: Date;
count: number;
type: "Add" | "Remove";
};
the "Type" can either be "Add" or "Remove". I had a boolean for this value previously, but the "Add" and "Remove" fit better to automatically have the legend say "Add" and "Remove". It could be changed back to a boolean if there is a better way to display it that way.
The data could be changed in other ways too, if that will simplify things. I am also open to using a D3.js implementation instead of Plot.plot.
I'm very new to Observable Plot.plot so any help is appreciated, thank you!
I want to draw a chart using ChartJS and Flask.
I can draw the chart when I set my variables directly into the JS part (i.e. when data: [1.03, 380.31, 0.0, 18.69, 400.02]), but not when I pass the data using Flask.
I have checked the variable passed to Flask, and I can show in the browser (with a p tag) that the content of the array is fine: [1.03, 380.31, 0.0, 18.69, 400.02]
The JS code is below, t_gamme and t_badge are both arrays (build in Python using append method):
new Chart(document.getElementById("chart-tps"), {
type: 'bar',
data: {
labels: ["A", "B", "C", "D", "TOTAL"],
datasets: [{
label: "Temps gamme (h)",
backgroundColor: "#3e95cd",
data: "{{ t_gamme }}"
}, {
label: "Temps badgé (h)",
backgroundColor: "#8e5ea2",
data: "{{ t_badge }}"
}]
},
options: {
legend: {
display: false
},
title: {
display: true,
text: 'Temps badgé versus temps gamme en heures'
}
}
});
I would like avoiding to make an AJAX call to an endpoint for getting these arrays because I have already.
I removed " character and it works, but I have errors in Javascript code in Visual Studio Code:
Related to ChesskoWarrior's answer:
I tried that solution, but still, get the red error on double brackets.
Here is an example that works for me:
1.) Python function in routes.py as part of the Flask-App:
def index():
data = {"labels": ['a', 'b', 'c', 'd'],
"data_1": [1, 2, 3, 4],
"data_2": [5, 6, 7, 8]}
return render_template('template.html', data=data)
2.) You can access this variable in template.html as {{ variable }}. This works in JS too. However, you need to create a new JS variable and make sure the data is formatted in the right way. Fortunately, there is a Jinja "tojson"-filter which converts the data into a proper JSON (https://flask.palletsprojects.com/en/1.1.x/templating/#standard-filters). Knowing this, this code snippet works for me inside the template.html:
{% block javascripts %}
<script>
var data_js = {{ data|tojson }};
...
});
</script>
{% endblock javascripts %}
Now you can access the data using the original keys:
datasets: [{
label: data_js["labels"],
data: data_js["data_1"]
}, {
label: data_js["labels"],
data: data_js["data_2"]
}]
I'm using the Highchart charting library with AngularJS, using Pablojim's 'Highchart-ng' module.
Everything is set up properly, and the following code works as intended:
<highchart config="{
type : 'line',
series : [{
name : 'Visitors',
data : [1, 4, 10, 3]
}]
}"></highchart>
But
<highchart config="{
type : 'line',
series : [{
name : 'Visitors',
data : {{visitors}}
}]
}"></highchart>
does not. (notice the difference at 'data')
I keep getting the following error:
Error: [$parse:syntax] Syntax Error: Token 'visitors' is unexpected, expecting [:] at column 122 of the expression [{
type : 'line',
series : [{
name : 'Visitors',
data : {{visitors}}
}]
}] starting at [visitors}}
}]
}].
Note: The variable {{visitors}} is set up properly in my controller, and when using it in my template, the data works fine. It also used to work with my previous charting library, Flot.
I've tried multiple workarounds:
Normally I can work around this (initialization) problem by adding something like ng-repeat="data in visitors | limitTo: 1" to the directive, so it inits only when the variable becomes available (this works with Flot and EasyPieCharts).
Adding ui-refresh="visitors" doesn't work,
and data: {{visitors || 0}} doesn't work either.
So, how can I add variables inline, within my template files?
you can try with:
<highchart config="{
type : 'line',
series : [{
name : 'Visitors',
data : visitors
}]
}"></highchart>
like a var
OR
in your ng-controller
$scope.config = {
options: {
chart: { type: 'bar' }
},
series: [{
data: visitors
}],
title: { text: 'Hello' },
loading: false }
and then in your html
<highchart config="config"></highchart>
I don't think I'm understanding JSON completely, here is my code:
$.ajax({
type: "POST",
url: baseurl + "analytics/grab_points"
}).done(function(data) {
console.log(data);
var line1=$.parseJSON(data);
console.log(line1);
var plot2 = $.jqplot('chartdiv', line1, {
title: 'Customized Date Axis',
gridPadding: {right: 35},
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {formatString: '%b %#d, %y'},
min: 'May 30, 2008',
tickInterval: '1 month'
}
},
series: [{lineWidth: 4, markerOptions: {style: 'square'}}]
});
});
jqPlot seems to expect data like so:
[['2008-06-28 8:00AM', 4], ['2008-6-30 8:00AM', 1], ['2008-8-30 8:00AM', 5.7]]
(that should the content in var line1)
My server side code (PHP):
$test=array(
"2008-06-28 8:00AM" =>4,
"2008-6-30 8:00AM" =>1,
"2008-8-30 8:00AM" =>5.7,
);
echo json_encode($test);
My console logs:
{"2008-06-28 8:00AM":4,"2008-6-30 8:00AM":1,"2008-8-30 8:00AM":5.7} analytics:103
Object {2008-06-28 8:00AM: 4, 2008-6-30 8:00AM: 1, 2008-8-30 8:00AM: 5.7} analytics:105
Uncaught Error: No data specified
Pretty sure I'm going barbarian on this JSON (growing pains), any idea would be great.
if you want to get the same structure that jqPlot wants you'll have to change your array in your php code...
jqPlot is expecting something like in your php array-structure:
$test = array(
array("2008-06-28 8:00AM",4),
array("2008-6-30 8:00AM",1)
);
check example 2 on http://php.net/manual/en/function.json-encode.php (the $c)
the {} you see is just because you output it as object rather than as array, but this should be the same as the [] (this is also explained on the php manual)
EDIT: also i don't think this line: var line1=$.parseJSON(data); is still needed because your data is already json.
I create a Column chart using Kendo ui dataviz.
In my program, i am going to bind the local Javascript Array variable data to chart datasource.
The JSON data was spilted like "3""9""6" for "396".
I dont know why it happened. My Source code is given blow. Please check it and Please give the solution.
Source:
/**************Variable Declaration**********************************/
var eligibilityData = new Array();
eligibilityData = {
mem_status: {
a: 396, b: "56", c: "1125", d: "8423"
}
};
/**************Create Chart**********************************/
function createBarChart(eligibilityData) {
/****** Issue: A value is 396 but it spilted into "3","9","6"************/
$("#Chart1").kendoChart({
theme : $(document).data("kendoSkin") || "default",
dataSource : {
data: JSON.stringify(eligibilityData.mem_status.a),
},
seriesDefaults: { type: "column", },
series : [
{ field: "a", name : "A" }
],
tooltip : { visible: true, },
});
}
Local data should be passed as an array. No need to call JSON.stringify
data: [eligibilityData.mem_status]
See: http://docs.kendoui.com/api/framework/datasource#configuration-data-Array
JSON.stringify does not do what you expect. What you sentence really does is:
It gets the number 396 and converts it to a string.
Converts a string into an array of one character per element.
Not sure about the way you define the DataSource (why you want a DataSource with only one element) but if that is really what you want, you might try:
dataSource : {
data: [eligibilityData.mem_status.a]
},
or
dataSource : {
data: [eligibilityData.mem_status]
},