Codeigniter getJSON not working in external Javascript file - javascript

I write some JS script directly at my header (I'm using codeigniter) and everything works correctly. But then I try to separate that script from header so I create JS file and put the script there. I call the JS file from header file but the getJSON function inside my script can not work properly.
Here is how I call the external JS file from header :
<script type="text/javascript" src="<?php echo base_url('asset/js/charts/v_soaotc_daily.js')?>"></script>
Here is my full JS :
$(function () {
$('#soaotc_daily_chart').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'SOA_OTC Daily'
},
xAxis: [{
categories: []
}],
yAxis: [{ // Primary yAxis
labels: {
// format: '{value} Rs.',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Amount',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'Population',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
//format: '{value} out of 100',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Population',
type: 'column',
yAxis: 1,
data: [],
tooltip: {
// valueSuffix: ' out of 100'
},
dataLabels: {
enabled: true,
// format: '{point.y:.0f}/100'
}
}, {
name: 'Amount',
type: 'spline',
data: [],
tooltip: {
valueSuffix: ''
}
}]
}, function(theChart){
$.getJSON("<?php echo base_url(); ?>soaotc/daily_json", function(json) {
alert('sukses');
theChart.xAxis[0].setCategories(json[0]['data']);
theChart.series[0].setData(json[1]['data'], false);
theChart.series[1].setData(json[2]['data'], true);
})
.fail( function(d, textStatus, error) {
console.error("getJSON failed, status: " + textStatus + ", error: "+error)
});
});
var theChart = $('#container').highcharts();
});
FYI only the getJSON function which can not work. Here is what I found in console :
getJSON failed, status: parsererror, error: SyntaxError: Unexpected token D
If the getJSON success, it will return JSON data like this :
[{
"name":"Date",
"data":["27-OCT-14","28-OCT-14","29-OCT-14","30-OCT-14","31-OCT-14","01-NOV-14","02-NOV-14"]
},
{
"name":"Population",
"data":[6171,6990,6882,6889,6860,7619,6698]
},
{"name":"Amount",
"data":[361154716.01,409210099.77,407191552.71,416366585.57,418588842.18,435168113.68,402163667.57]
}]
Am i miss something in my code? or is there some config in codeigniter which allow us to call external JS file that i missed? Appreciate for your help.

Method 1:
You need to remove backslashes if there any in the url. See here Same bug
Method 2:
You can use $.post(url,data,function(json){...}) instead of getJson and use dataType : json with echo json_var from the controller page.

Problem has been solved in very simple way. I replace the URL in
$.getJSON("<?php echo base_url(); ?>soaotc/daily_json", function(json){..});
to
$.getJSON("daily_json", function(json){..});
Thank you.

Related

Highcharts.chart is not a function?

I am getting the json data but its not showing in jsp page. In console Uncaught TypeError: Cannot read property 'navigator' of undefined exporting.js:9 and export-data.js:10 Uncaught TypeError: Cannot read property 'document' of undefined and highcharts.chart is not a function
I have copy the highchart js file in my local path
<script src="${resourceUrl}/js/highchart/highcharts.js"></script>
<script src="${resourceUrl}/js/highchart/exporting.js"></script>
<script src="${resourceUrl}/js/highchart/export-data.js"></script>
<script>
$(document).ready(function(){
$.getJSON( "http://localhost:8080/mandatoryCheck/generate2", function(data) {
var chart = new Highcharts.chart('cvsMandCheckGraph', {
chart: {
type: 'column'
},
title: {
text: 'Top 5 Mandatory Checks Fail'
},
subtitle: {
text: ''
},
xAxis: {
categories: " ",
crosshair: true
},
yAxis: {
min: 0,
title: {
text: ''
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
shadow: true
},*/
series: [{
colorByPoint: true,
data: data
}]
});
});
});
$(document).ready(function(){
$.getJSON( "http://localhost:8080/fieldModification/generate", function(data) {
var chart = new Highcharts.chart('cvsFieldModiChart', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
legend: {
itemStyle: {
fontSize: '10px'
}
},
subtitle: {
text: 'Top 5 Field Modifications'
},
xAxis: {
categories: []
},
tooltip: {
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{}</b><br>{point.percentage:.1f} %',
distance: -30,
color: '#fff',
style: {
textOutline: false ,
fontSize: 9,
},
filter: {
property: 'percentage',
operator: '>',
value: 4
}
},
showInLegend: true
}
},
series: [{
name: '',
style: { fontFamily: '\'Lato\', sans-serif', lineHeight: '18px', fontSize: '17px' },
colorByPoint: true,
data: data
}]
});
});
});
</script>
You can make use of below CDN link.It will make sure the Highchart.chart is available.
If you are using jQuery make sure that jQuery CDN link should provide before Highchart Link
console.log(Highcharts.chart)
<script src="http://code.highcharts.com/highcharts.js"></script>

Drawing a dynamic Mixed Bar and Line chart with HIghchart.js with socket.io for live data

I am trying to draw a dynamic, mixed bar and line graph using Highchart.js. I am getting live data to my webpage using socket.io (I'm using Flask as my webserver so using Flask-socketIO).
I am able to print the data coming to my webpage using console.log, but I am missing something for which it is not rendered in the chart.
I am trying to add xAxis as well as both the Series value.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<link href="../static/css/authz.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myChart = Highcharts.chart('containerX', {
chart: {
zoomType: 'xy',
events: {
load: function () {
// set up the updating of the chart on each sample
var categories = this.xAxis[0].categories;
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
var series1 = this.series[0]
var series2 = this.series[1]
socket.on('my_response_data', function (sample) {
//add chart data to series
var x = sample.logTime
var y = sample.logDuration
var z = sample.totalSession
console.log( x + " " + y + " " + z) //Printing properly to console e.g 2018-01-25T03:58:35.781 3 211
categories.push(sample.logTime)
series1.addPoint(y, false, true);
series2.addPoint(z, false, true);
myChart.redraw();
});
}
},
},
title: {
text: 'Sacred Tests'
},
subtitle: {
text: 'Source: My Secret Source'
},
xAxis: [{
categories: [],
crosshair: true
}],
yAxis: [{ // Primary yAxis
title: {
text: 'Sessions',
style: {
color: Highcharts.getOptions().colors[1]
}
},
labels: {
format: '{value}',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'Duration',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} ms',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Sessions',
type: 'column',
yAxis: 1,
data: [],
tooltip: {
valueSuffix: ''
}
}, {
name: 'Duration',
type: 'spline',
data: [],
tooltip: {
valueSuffix: 'ms'
}
}]
});
});
</script>
</head>
<body>
<div id="containerX" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
It's a problem with displaying only one point at a time with addPoint(point, redraw, shift, animation) and setting shift=true. That will remove previous point and chart will look empty.
Simple solution is to use:
series1.addPoint(y, false, false, false);
series2.addPoint(z, false, false, false);
myChart.redraw();

How to pass a value into javascript array?

I am working on a pie chart for the admin dashboard to display some data about the users. I am getting the response from PHP file correctly and store it in result_from_PHP variable as you can see the code below. My problem is, I don't know how to pass this variable result_from_PHP to the series part in the code y: result_from_PHP. Can anyone help please ?
<script type="text/javascript">
$.getJSON("PHP_trader_behav.php", function(data){
$.each(data.result,function(){
var result_from_PHP = this['visitors_count'];
alert(result_from_PHP);
$(function () {
alert(result_from_PHP);
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: 'Microsoft Internet Explorer',
y: result_from_PHP
}, {
name: 'Chrome',
y: 5000,
sliced: true,
selected: true
}, {
name: 'Firefox',
y: 1000
}, {
name: 'Safari',
y:1000
}, {
name: 'Opera',
y: 4000
}, {
name: 'Proprietary or Undetectable',
y:3000
}]
}]
});
});
});
});
</script>
TRY THIS ONE
y: <?PHP echo result_from_PHP ?>
you have do whatever your wish with in the php tag
Build series array[in the form of json] using $.each , then use that variable into $('#container').highcharts({series:some-variable})
you can study the below link:
JavaScript Arrays

Can`t place on the X axis, dates from ms sql server

$(function () {
Highcharts.setOptions({
global : { useUTC : false
}
});
$('#container').highcharts({
title: {
text: 'coefficient 10 days',
x: -20
},
subtitle: {
text: 'Company',
x: -20
},
xAxis: {
categories: [<?php echo join($data, ',')?>],
type: 'datetime'
},
yAxis: {
title: {
text: 'Коэффициент'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '', enabled: false
},
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom',
borderWidth: 0
},
series: [
{
name: 'value',
data: [<?php echo join($koef, ',')?>]
}, {
name: 'norm',
data: [<?php echo join($norm, ',')?>], color: '#FF0000'
}
]
});
});
When format in php as 'Ymd', date is correct but as number, like '20151210' this not readable for users. When i try format (in php code) 'd.m.Y' java say script1007 error. On api.highcharts.com nothing in the description specified what to do. Probably i need set in javascript something about datetime setting.

Highcharts not able to access z value

$(function () {
$('#containerGraph').highcharts({
chart: {
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: ''
},
exporting: { enabled: false },
credits: { enabled: false },
xAxis: {
type: 'category',
title: {
text: 'Date'
},
labels: {
rotation: -45,
style: {
fontSize: '10px',
fontFamily: 'Verdana, sans-serif'
}
}
},
plotOptions: {
column: {
colorByPoint: true
}
},
yAxis: {
min: 0,
title: {
text: 'Time (minutes)'
}
},
legend: {
enabled: false
},
tooltip: {
//pointFormat: '<b>{point.y:.1f} minutes</b>{point.x:}'
formatter: function() {
return '<b>'+ this.y +'</b>'+
'minutes<br>'+ this.point.z + 'hi' ;
},
//shared: true
},
series: [{
name: 'Time',
data: [
['<?php print $buildDate[0]?>', <?php print $lastFifteenDurationArray[0]?>, <?php echo $svnHistory[0]?>],
['<?php print $buildDate[1]?>', <?php print $lastFifteenDurationArray[1]?>, <?php print $svnHistory[1]?>],
['<?php print $buildDate[2]?>', <?php print $lastFifteenDurationArray[2]?>, <?php print $svnHistory[2]?>],
['<?php print $buildDate[3]?>', <?php print $lastFifteenDurationArray[3]?>, <?php print $svnHistory[3]?>],
['<?php print $buildDate[4]?>', <?php print $lastFifteenDurationArray[4]?>, <?php print $svnHistory[4]?>],
['<?php print $buildDate[5]?>', <?php print $lastFifteenDurationArray[5]?>, <?php print $svnHistory[5]?>]
],
lang: {noData: "No Data Available"},
dataLabels: {
enabled: false
}
}]
});
});
The value of z-axiz in the tooltip shows Undefined in the chart.
I also tried this.point.config[2], but that doesn't work either.
When I debugged the code, the z-value in the data field is correctly resolved.
Is it because I have to specify type of data or something?
Can someone tell me what I am doing wrong?
In case you wan't a third dimension you'll need to define it like this: data = [{y: yValue, z: zValue, additional: additionalVal}], like this you can access this.point.z (and this.point.additional). Anyway, it seems that using the series X values as x-axis category label does not work while working with an array of objects. In order to make it run, do it like this:
xAxis: {
type: 'category',
categories: ['09-01-2015','09-01-2015'], /* your old x-data */
title: {
text: 'Date'
}
},
series: [{
name: 'Time',
/* data is now an array of objects */
data: [
{y:25, z:492076},
{y:26, z:496222}
],
}
updated Fiddle is here

Categories