JSON encode data not parsing to JqPlot Chart in PhP script - javascript

I have been searching stack overflow and other sites on this one for a few days and can't find enough information to solve my exact problem.
I have also referred to 'create web charts with JqPlot' by Fabio Nelli, while a great book it does not address my circumstances.
I do not have a great grasp of java script which may be some of my problem.
I am trying to get some data charted into a bar graph and think that the data is not getting encoded to JSON in the required format leading to the failure.
I may also not have my JavaScript component of my php document structured correctly.
(My source MySQL data is being handled by PhP and builds the required table - my theory behind this is to pull a table up and use to compare with a JqPlot Chart).
My bits of relevant code
Head:
<script type='text/javascript'> chart_data = ".json_encode($data_array).";</script>
Body (after fetching php variables as array through a html form filtering the data)
// creates array for json_encode
$data_array [] = array($inj_data2['count'], $damage_data2['count']);
Section that outputs the chart canvas and hopefully colorful data (using Bootstrap)
print ("<div class='panel-group'>
<div class='panel panel-default'>
<div class='col-sm-6 col-md-6 col-lg-6'><div class='row'><div id='chartdiv'></div>");
And for page loading speed the Jq Plot is at the foot of the script:
?>
</body> <!-- side bar chart source info http://www.jqplot.com/examples/barTest.php# !-->
<script type="text/javascript" src="jquerychart/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jquerychart/jquery.jqplot.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.barRenderer.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.pieRenderer.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.categoryAxisRenderer.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.pointLabels.js"></script>
<link rel="stylesheet" type="text/css" href="jquerychart/jquery.jqplot.css" />
<script>
$(document).ready(function(){
var plot4 = $.jqplot('chartdiv', [chart_data],
{
stackSeries: true,
captureRightClick: true,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
shadowAngle: 135,
rendererOptions: {
barDirection: 'horizontal',
highlightMouseDown: true
},
pointLabels: {show: true, formatString: '%'}
},
legend: {
show: true,
location: 'e',
placement: 'within'
},
title:"Incidents by Department",
axes: {
yaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
});
</script>
</html>
I have checked the json_encode array with
print json_encode($data_array);
And this is output to the browser
[["5","1"],["1","1"],["1","0"]]
These data sets are what I am after, however I believe the " " symbols are what is causing the issue?
I also wish to be able to create labels based on variables (expecting this will require JSON also) and would appreciate pointers on this.
My constraints are that I do not want any AJAX calls and wish to be able to pass all the data within the php script this is written in.
The current code returns a blank canvas below the table, and Firebug console returns:
Error: No data specified
All feedback will be greatly appreciated, please remember JavaScript is not a strong point for me.
The chart also works if data is manually input to the code (ruling out any basic issues around resources).
Cheers Jase

I have solved the problem (99%) I had - it may not be pretty or technically correct ..... if it can be improved upon please let me know......
Converting the variables to an array and removing the double quotes - I needed to declare each variable as the variable type within the array.
Within the php body
$data_array [] = array((int)$inj_data2['count'],(int)$damage_data2['count']);
This was the bit that stumped me for days...
Convert the php array into a JSON object using json_encode.
I knew I had to create a javascript object but a little stuck.
I was mistakenly missing out the php tags in the javascript
My fix was to place this code in the foot (after the body close tag) of he document like this:
<script type='text/javascript'> var chart_data = <?php echo json_encode($data_array);?></script>
Then declare this javascript variable within the JqPlot code like this:
var plot4 = $.jqplot('chartdiv', chart_data,
{
Hopefully this can assist someone in the future I still need to work out how to add the required text labels from variables.
Cheers Jase

Related

How to use Highcharts in a WordPress website Report this postQuote

I am Yi. I want to use Highcharts on my Wordpress site to make this kind of chart. I stuck in the very first Installation step. I ask Hightcharts service team & Black Label Team, they recommend me to reaching out here. :(
I need some advices about my next steps.
What I have tried&done:
I Read Highcharts document and pasted thest code in the head section of my web page.
I read the document, pasting these codes in the head:
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="/js/highcharts.js"></script>
<script src="/js/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
I pasted the codes like this:enter image description here
I downloaded Highchart Stock 9.3.1 zip file and uploaded some of them on Cpanel.
I downloaded Highchart Stock 9.3.1 zip file. Create a new folder named Highcharts in public_html/wp-content/plugins. Uploaded js files which I think is important in 9.3.1 zip to this Highcharts file.
Like this:enter image description here
I am wondering since I will use highcharts stock, should I type highstock.js instead of highcharts.js?
Then codes included in the head section will be like:
A. INCLUDE HIGHCHARTS#
<script src="https://code.highcharts.com/highstock.js"></script>
B. ALTERNATIVELY, LOAD FILES FROM YOUR OWN DOMAIN#
<script src="/js/highstock.js"></script>
C. LOAD HIGHCHARTS STOCK OR HIGHCHARTS MAPS#
<script src="/js/highstock.js"></script>
That what I have done. I need some advices from people who are familiar with wordpress and highcharts. Thanks.
Upload the script to a WordPress template or use a plugin like wpDataTables which allows you to select many type of charts and edit them.
You should use highstock.js if you chosen Highcharts Stock
<script src="https://code.highcharts.com/stock/highstock.js"></script>
I find the way to add javascript on my website and finally built my first a Highcharts chart! I am not a developer so I don't know whether it is the correct way or not. But if someone faced the same problem like me, you can try it.
1)Download 'Insert Headers and Footers' plugin. and type these in the section.
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="/js/highstock.js"></script>
2)Download 'Code Embed' plugins.
3)Enter the javascript code in the 'New Custom Field' build by Code Embed.
//**This my example you can try it**//
<script>Highcharts.getJSON('https://demo-live-data.highcharts.com/aapl-c.json', function (data) {
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Stock Price'
},
series: [{
name: 'AAPL',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
});</script>
4)follow the Code Embed document to call the chart.

Write hyperlink so that an html file loads but internal link to js file changes

This is a general question for which I have searched high and low to no avail, and would greatly appreciate any input.
I have a html/javascript educational quiz that loads a separate js file to retrieve an array to determine the content of the quiz. For example this retrieves the js file with an array of hard level math problems
<script type="text/javascript" src="../js/arrays/math-hard.js"></script>
I have a number of js files with arrays of different content. Another one might load English questions, etc. I need to have a variety of these quizzes, all launched from separate links in different sections of an overall interface.
Currently to create a new quiz I am duplicating the html file and changing the reference to point to the requisite js file for the array.
I would much prefer to have a single html file, and simply write different links that all load that same single html file, but dynamically substitute one of the other js array files to change the content. I cannot figure out how to do this, nor have I been able to find a published solution anywhere.
At the moment the html file is written such that it only references one of the js files that have the arrays, but it's fine to include links to all of them in that single file if that's necessary as part of achieving this functionality.
Currently I have a single html file (stripped down)
<!doctype html>
<html>
<head>
<script type="text/javascript" src="../js/quiz.js"></script>
<script type="text/javascript" src="../js/gridquiz/s-english-easy.js"></script>
</head>
<body>
<div id="gridQuizContent" class="quiz-content">
<div id="divClick" class="quiz-click"></div>
</div>
</div>
</body>
</html>
and it load that english-easy.js, that looks basically like this (simplified)
Quiz.easy = [
['hi-IN', 'dog', 'cat', 'pig', 'cow'],
['hi-IN', 'me', 'you', 'he', 'she'],
['hi-IN', 'up', 'down', 'in', 'out'],
['hi-IN', 'hot', 'cold', 'big', 'small'],
];
And I want to write many links that simply load the same html file but change this line
<script type="text/javascript" src="../js/gridquiz/s-english-easy.js"></script>
as it loads to reference a different array.
If each quiz URL looks similar to the following:
https://quiz.com/quiz.html?quiz=math-hard
https://quiz.com/quiz.html?quiz=math-easy
https://quiz.com/quiz.html?quiz=history-hard
Then you could possibly dynamically load the desired JavaScript file in a 'base' JavaScript file for quizzes by checking the URL path:
// base.js
function dynamicallyLoadScript(url) {
// create a script DOM node
var script = document.createElement("script");
// set its src to the provided URL
script.src = url;
/* add it to the end of the head section of the page (could change 'head'
to 'body' to add it to the end of the body section instead) */
document.head.appendChild(script);
}
let params = new URLSearchParams(location.search);
if (params.has('quiz')) {
dynamicallyLoadScript(params.get('quiz') + ".js");
}
So the HTML of https://quiz.com/quiz?quiz=math-hard would be similar to:
<!doctype html>
<html>
<head>
<script src="../js/base.js"></script>
<!-- Added by 'base.js' -->
<script src="../js/arrays/math-hard.js"></script>
</head>
<body>
</body>
</html>
Personally I would use JSON files to realize this. I found a tutorial on this website, which follows the same problem "how to store quiz questions".

get variable from csv file for HTML code using Javascript or jquery function

I want to have different numbers in my html code depending on a .csv file, so I want to be able to grab data from a .csv file to an html page using jquery or java script. I thought I found a webpage that shows how to do this in Jquery, but I can not figure it out. This webpage is at: http://code.google.com/p/jquerycsvtotable/
On the left side of this webpage there is even a download .zip file that should give me a working model of what this site describes, with even the final index.html file, but I can not get it to work. Could someone please show me what has changed or what I am doing wrong? Please, show me what I need to do to get this to work or give me another small example. I am new to JavaScript and Jquery.
( I finaly decided to post this question with this example page because this is the closest answer I have found to my question)
thanks
Tom,
Jay here is the code:
I have made sure JavaScript is enabled on the firefox brozer I use to test my file and I have a test.csv file sitting in the directory. This actually gives me the same result as if I download the .zip file from the left side of the website. It gives me an .html page with a link to a test.csv file which I can download, but it does not use the data in the code to make a table or do anything else?
thanks,
tom
enter code here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery CSVToTable</title>
<link rel="stylesheet" href="css/csvtable.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.csvToTable.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.dev.js"></script>
<script>
$(function() {
$.get('test.csv', function(data) {
$('#CSVSource').html('<pre>' + data + '</pre>');
});
$('#CSVTable').CSVToTable('test.csv', { loadingImage: 'images/loading.gif', startLine: 0 });
$.get('test.tsv', function(data) {
$('#TSVSource').html('<pre>' + data + '</pre>');
});
$('#TSVTable').CSVToTable('test.tsv', { loadingText: 'Loading TSV Data...', loadingImage: 'images/loading.gif', startLine: 0, separator: "\t" });
$('#CSVTable2').CSVToTable('test.csv', { loadingImage: 'images/loading.gif', startLine: 1, headers: ['Album Title', 'Artist Name', 'Price ($USD)'] }).bind("loadComplete",function() {
$('#CSVTable2').find('TABLE').tablesorter();
});;
});
</script>
</head>
<body>
[back to google code...]
<br><br>
This is a test of the CSVToTable plugin.
<br><br>
Original CSV Source of test.csv:<br>
<div id="CSVSource" style="background-color: #FAFAFA; border: 1px solid #999999">
</div>
<br><br>
CSV To Table:<br>
<div id="CSVTable">
</div>
CSV To Table2:<br>
<div id="CSVTable2">
</div>
</body>
</html>
A few general things to check:
Keep your console open in dev tools of your choice, ensure there are no Javascript errors occurring.
Again inside your dev tools, go to your network tab and look at the raw response that is being retrieved when the $.get occurs. Is it even able to retrieve it?
Check that your server is able to serve .csv files. It may be locked down to only serve certain mime types.
Without more info, it's hard to give you a more formal answer. Good luck with your app.

Uncaught TypeError: undefined is not a function while using jQuery UI

I haven't used jQuery before, and I wanted to use DateTimePicker plugin on my web page.
I downloaded the plugin file and placed them in the same directory as the HTML files.
I directly applied the code at How to use it? in http://xdsoft.net/jqplugins/datetimepicker/.
It threw the following error.
Uncaught TypeError: undefined is not a function pixelcrawler:61 (anonymous function)
My code follows.
<script type='text/javascript' src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="file:///jquery.datetimepicker.css"/ >
<script src="file:///jquery.datetimepicker.js"></script>
<script>
jQuery('#datetimepicker').datetimepicker();
</script>
<div class="container">
<div class="text-center">
<div class="page-header">
<h1>${conf['title']} <small>${conf['description']}</small></h1>
</div>
</div>
<div class="text">
<input id="datetimepicker" type="text" >
.
.
.
.
.
I could not figure out what the problem was. I have tried many other seemingly likely options, but it just did not work either.
(The ${} tags are used for the Mako template language. I am using Cherrypy.)
UPDATE:
I figured out the source of the problem.
It's from jQuery('#datetimepicker').datetimepicker();.
When tested, the datetimepicker() function was undefined. Maybe the way I imported the library was wrong?
jQuery(document).ready(function(){
jQuery('#datetimepicker').datepicker();
})
I don't know your file-structure. I never include local files like this as I use relative URLs from the start rather than having to change everytime I'm ready to use the code, but it's likely one of the files isn't being loaded in. I've included the standard datepicker below using Google CDN's jQuery UI. Does your console log any resources not found?
I think your jQuery is loaded OK, because it's not telling you jQuery is not defined so it's one of your files.
BTW, PHP gets the home URL:
$home="http://" . $_SERVER['HTTP_HOST'].'/';
Demo code datepicker, jQuery UI:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#datetimepicker').datepicker();
})
</script>
<input id="datetimepicker" type="text">
This is about the HTML parse mechanism.
The HTML parser will parse the HTML content from top to bottom. In your script logic,
jQuery('#datetimepicker')
will return an empty instance because the element has not loaded yet.
You can use
$(function(){ your code here });
or
$(document).ready(function(){ your code here });
to parse HTML element firstly, and then do your own script logics.
use jQuery.noConflict()
var j = jQuery.noConflict();
j(document).ready(function(){
j('#datetimepicker').datepicker();
})
For my situation, it was a naming conflict problem. Adding $J solves it.
//Old code:
function () {
var extractionDialog;
extractionDialog = $j("#extractWindowDialog").dialog({
autoOpen: false,
appendTo: "form",
height: "100",
width: "250",
modal: true
});
$("extractBomInfoBtn").button().on("click", function () {
extractionDialog.dialog("open");
}
And the following is new code.
$j(function () {
var extractionDialog;
extractionDialog = $j("#extractWindowDialog").dialog({
autoOpen: false,
appendTo: "form",
height: "100",
width: "250",
modal: true
});
$j("extractBomInfoBtn").button().on("click", function () {
extractionDialog.dialog("open");
});
});
Hope it could help someone.
Usually when you get this problem, it happens because a script is trying to reference an element that doesn't exist yet while the page is loading.
As richie mentioned: "The HTML parser will parse the HTML content from top to bottom..."
So you can add your JavaScript references to the bottom of the HTML file. This will not only improve performance; it will also ensure that all elements referenced in your script files have already been loaded by the HTML parser.
So you could have something like this:
<html>
<head>
<!-- Style sheet references and CSS definitions -->
</head>
<body>
<!-- HTML markup and other page content -->
<!-- JavaScript references. You could include jQuery here as well and do all your scripting here. -->
</body>
</html>
You may see if you are not loading jQuery twice somehow. Especially after your plugin JavaScript file loaded.
I has the same error and found that one of my external PHP files was loading jQuery again.
The issue because of not loading jquery ui library.
https://code.jquery.com/ui/1.11.4/jquery-ui.js - CDN source file
Call above path in your file.
And if you have this problem in slider or slideshow you must use jquery.easing.1.3:
<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>
I had trouble getting selectable to work with ASP.NET. It turns out I wasn't properly including everything, but this gentleman made it foolproof: Three steps to use jQuery UI in ASP.NET MVC 5.
I don't think jQuery itself includes datetimepicker. You must use jQuery UI instead (src="jquery.ui").

My Jqplot pie chart is being displayed without any color for the small table inside the pie chart

i am using Jqplot pie chart inside my asp.net MVC 3 web application , but the problem is that the small table inside the pie chart which contains the chart label are being display without any color.
So how i can solve this issue?.
Thanks in advance for any help.
BR
Edited
thanks for ur kind reply, yes i have included these files , but still no colors are shown. here is the code inside my MVC 3 asp.net web application(the pie chart shows two values ;the percentage of students who like a test to the students who did not provide any Rating ).
<script src="../../Scripts/jqplot/jquery.jqplot.min.js" type="text/javascript"></script>
<script src="../../Scripts/jqplot/jqplot.pieRenderer.min.js" type="text/javascript"></script>
<script src="../../Scripts/jqplot/jqplot.donutRenderer.min.js" type="text/javascript"></script>
<script src="../../Scripts/jqplot/jqplot.barRenderer.min.js" type="text/javascript"></script>
<script src="../../Scripts/jqplot/jqplot.categoryAxisRenderer.min.js" type="text/javascript"></script>
<script src="../../Scripts/jqplot/jqplot.pointLabels.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var data = [
['Number of Like', #ViewBag.CountRate], ['Other', #ViewBag.other]
];
var plot1 = jQuery.jqplot('r1', [data],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
}
},
legend: { show: true, location: 'e' }
}
);
});
</script>
<div id = "r1"></div>
jqPlot documentation doesn't mention it very strongly but it does mention to include the css file
To use jqPlot include jquery, the jqPlot jQuery plugin, jqPlot css
file and optionally the excanvas script for IE support in your web
page
So you need to include jquery.jqplot.min.css e.g.
<link rel="stylesheet" href="/jqplot/jquery.jqplot.min.css">
Also jqPlot recommends using css to customize colors etc see http://www.jqplot.com/docs/files/jqPlotCssStyling-txt.html
are you loading all the required js files? sounds like you are missing:
jqplot.pointLabels.min.js
add these:
("~/scripts/jqPlot/jquery.jqplot.min.js")
("~/scripts/jqPlot/plugins/jqplot.pieRenderer.min.js")
("~/scripts/jqPlot/plugins/jqplot.donutRenderer.min.js")
("~/scripts/jqPlot/plugins/jqplot.barRenderer.min.js")
("~/scripts/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js")
("~/scripts/jqPlot/plugins/jqplot.pointLabels.min.js")

Categories