PHP to JavaScript Chart; display w/button - php

The charts I am using are written in JavaScript, so I need to transfer mysql query arrays to JavaScript, creating the charts. The mysql queries are generated by drop down menus. On the web page is a button that, when clicked, should display the chart. All should be displayed on the same page.
I have two drop down menus with names of runners in each. through onChange, each drop down menu calls the same JavaScript function -
home.php
<form id='awayPick'>
<select name='awayRunner' id='awayRunner' onchange='Javascript: getitdone(this);/>
...multiple options
</form>
<form id='homePick'>
<select name='homeRunner' id='homeRunner' onchange='Javascript: getitdone(this);/>
...multiple options
</form>
Js.js
function getitdone(str)
{
if (str=="")
{
document.getElementById("midSpa").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp11=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp11=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp11.onreadystatechange=function()
{
if (xmlhttp11.readyState==4 && xmlhttp11.status==200)
{
document.getElementById("midSpa").innerHTML=xmlhttp11.responseText;
}
}
var awayRunner = document.getElementById('awayRunner').value;
var homeRunner = document.getElementById('homeRunner').value;
var queryString = "?awayRunner=" + awayRunner + "&homeRunner=" + homeRunner;
xmlhttp11.open("GET","getRunners.php" + queryString,true);
xmlhttp11.send(null);
}
getRunners.php
$home=$_GET['homeRunner'];
$away=$_GET['awayRunner'];
$db = db;
$homeRunner=array();
$awayRunner = array();
$leagueRunner = array();
$getHome="select ... from $db where ... = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['...'];
}
$getAway="select ... from $db where ... ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['...'];
}
$week = 0;
while($week<20){
$week++;
$getLeague = "select ... from $db where ... = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$leagueRunner[]=$row3['...'];
}
}
home.php
<script type="text/javascript">
function chartOne(){
$(document).ready(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo:'container',
zoomType:'xy' },
title: {
text:
'title'
},
xAxis: {
categories: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
},
yAxis: [{ // Primary yAxis
labels: {
formatter: function() {
return this.value + 'pts'
},
style: {
color: '#89A54E'
}
},
title: {
text: 'text',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text:null,
},
}],
tooltip: {
formatter: function() {
return '' +
this.y +
(this.series.name == ' ' ? ' mm' : 'pts');
}
},
legend: {
layout: 'horizontal',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 69,
y: 20,
floating: true,
shadow: true,
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [ {
name:'adfg',
data: [ <?php echo join($awayRunner, ',');?>],
type: 'column',
pointStart: 0
//pointInterval
},
{
name:'fghtrht',
data: [<?php echo join($homeRunner, ',');?>],
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [ <?php echo join($leagueRunner, ',');?>],
type:'spline',
pointStart: 0
//pointInterval
},
]
});
});
}
</script>
<input type='submit' value='chart One' onclick='chartOne()'></input>
<div id='container' style='width: 50%; height: 200px; float: left;'></div>
How do I get the php arrays back to the home page into the javascript? Should I place the JavaScript somewhere else?
The thing is, I have gotten all of this to run on separate pages when I didnt try to pass the runners names through. If I explicitly stated the runners names on the getRunners.php page, everything works great. I can not get the the php variables to insert into the JavaScript to generate the charts.
I've tried to assign the js code to a php variable in the getRunners.php page then echo the variable on the home.php page which didnt work.
It seems, once the home page is loaded, the JS remains the same. How do I pass through the PHP variables after the drop down options have been selected, allowing the chart to be displayed only after the button is clicked?
Thank you. I hope this is more clear than my previous question.

here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Related

What wrong, fullcalendar JSON feed not showing while use eventSources

Like everyone else I also have problem when displaying event in fullcalendar.
Below is my controller for JSON data:
function schedule($id) {
$data = $this->M_care->getSchedule($id);
echo json_encode($data);
exit;
}
This controller produce JSON data like that:
[{"id":"51","title":"test date","start":"2022-03-31T00:00:00-05:00","end":"2022-03-31T00:00:00-05:00"},{"id":"53","title":"test date","start":"2022-03-29T00:00:00-05:00","end":"2022-03-29T00:00:00-05:00"}]
and below is script for render calendar:
document.addEventListener('DOMContentLoaded', function() {
var initialLocaleCode = 'id';
var calendarEl = document.getElementById('calendar');
var url = '<?= base_url('service/Care/schedule/').$id; ?>';
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
validRange: function(nowDate) {
return {
start: nowDate
};
},
eventSources: [
{
url: url,
color: 'red',
textColor: 'black',
display: 'background'
}
]
});
calendar.render();
});
The $id in the url variable get from $id = $this->session->userdata('event');
Above code is not working for displaying events data. I have trying to solve this for several days, and search related question but none of them fix this issue.

How to use foreach loop in php for retrieve data from data base to jquery-ui accordion

How to use foreach loop in php for retrieve data from data base to jQuery-ui accordion. I want to user jQuery accordion for fetch data from database. I tried many ways but I can't to do that because of lack of my knowledge. I used jQuery-ui for this one.
This is the code I wrote for this
<body>
<div class="container" style="width:900px;">
<div id="accordion"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.ajax({
url: "fetch.php",
method:"POST",
dataType: "json",
success: function(data)
{
console.log(data);
$( function() {
$( "#accordion" ).accordion();
//console.log(data);
var device_ID;
var sensor_ID;
} );
}
});
});
</script>
This is the PHP part:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "kapra_iot");
$query = "
SELECT * FROM `view_sensor`
";
$result = mysqli_query($connect, $query);
//$output = array();
while($row = mysqli_fetch_array($result))
{
$sub_data["device_ID"] = $row["device_ID"];
$sub_data["device_Name"] = $row["device_Name"];
$sub_data["sensor_ID"] = $row["sensor_ID"];
$sub_data["sensor_Name"] = $row["sensor_Name"];
$sub_data["lower_Value"] = $row["lower_Value"];
$sub_data["mid_Value"] = $row["mid_Value"];
$sub_data["upper_Value"] = $row["upper_Value"];
$data[] = $sub_data;
}
foreach($data as $key => &$value)
{
$output[$value["device_ID"]] = &$value;
}
foreach($data as $key => &$value)
{
if($value["sensor_ID"] && isset($output[$value["sensor_ID"]]))
{
$output[$value["sensor_ID"]]["nodes"][] = &$value;
}
}
foreach($data as $key => &$value)
{
if($value["sensor_ID"] && isset($output[$value["sensor_ID"]]))
{
unset($data[$key]);
}
}
echo json_encode($data);
//echo '<pre>';
//print_r($data);
//echo '</pre>';
?>
I'd point you to the docs just as Kumar Praveen did. The Accordion will display the different sections titles using the h3 tag and the inner section of each one inside div tags.
Loop trough the result and add it to your accordion div following the syntax described before.
$(document).ready(function () {
$.ajax({
url: "fetch.php",
method: "POST",
dataType: "json",
success: function (data) {
for (device in data)
{
$("#accordion").append("<h3>"+device['device_id']+" " + device['device_Name'] + "</h3>");
$("#accordion").append("<div><p> Insert here all the relevant data of your device including all the other variables</p></div>");
}
$("#accordion").accordion();
}
});
});
Using the Widget Factory, you can extend accordion to a remote source.
$(function() {
var testData = [{
"device_ID": 1001,
"device_Name": "Device 1",
"sensor_ID": 597,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 50,
"upper_Value": 100
}, {
"device_ID": 1002,
"device_Name": "Device 2",
"sensor_ID": 598,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 500,
"upper_Value": 1000
}, {
"device_ID": 1003,
"device_Name": "Device 3",
"sensor_ID": 599,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 0.05,
"upper_Value": 0.1
}];
$.widget("custom.buildList", $.ui.accordion, {
options: $.extend(this.options, {
source: "",
data: []
}),
_create: function() {
console.log("Init");
this.element.addClass("custom-list");
var action;
if (this.options.source == "") {
action = "html";
} else if (typeof this.options.source == "string") {
action = "ajax";
} else {
action = "array";
}
console.log("Action", action);
if (action !== "html") {
if (action === "ajax") {
this.options.data = this._getData(this.options.source);
}
this._makeList(this.element);
}
console.log("Return to _create");
return this._super();
},
_getData: function(url) {
console.log("Getting Data", url);
$.getJSON(url, function(resp) {
this.options.data = resp;
});
},
_makeList: function(tObj) {
console.log("Making List");
var myData;
if (this.options.data.length == 0) {
myData = this.options.source;
} else {
myData = this.options.data;
}
console.log("List Data", myData);
$.each(myData, function(i, d) {
var hd = $("<h3>").html(d.device_Name);
var bd = $("<div>");
var ls = $("<ul>").appendTo(bd);
$.each(d, function(k, v) {
$("<li>").html(k + ": " + v).appendTo(ls);
});
tObj.append(hd, bd);
});
}
});
$("#accordion").buildList({
source: testData
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container" style="width:900px;">
<div id="accordion"></div>
</div>
This extension allows a URL or Array to be passed in as a Source option. So if you wanted to use it to get data from a PHP Script, you could do:
$("#accordion").buildList({
source: "fetch.php"
});
The extended widget will collect the data from the URL or Array and build the needed HTML before calling on the rest of the widget. I had to test with an array. You will also need to modify _makeList() function to meet you various needs.
It is also built to default back to HTML if you so choose. Also you have all the same options as you would with a standard Accordion widget.

Google combo chart issue

I am trying to create a combo chart using google charts,
in HTML added below CDN and div
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: auto; height: 500px;"></div>
the result of
var examname = <?php echo json_encode($examnames); ?>;
var highestScore = <?php echo json_encode($heighestScores); ?>;
var userScore = <?php echo json_encode($userScores); ?>;
is
var examname = ["Test Name 1", "Full Test", "Knowledge"];
var highestScore = ["8", "11", "10"];
var userScore = ["6", "11"];
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var graphData = new google.visualization.DataTable();
graphData.addColumn('string', 'TestName');
graphData.addColumn('number', 'Height');
graphData.addColumn('number', 'YourScore');
for (var i = 0; i < examname.length; i++) {
if (userScore[i] === undefined) {
userScore[i] = 0;
}
console.log(userScore[i]);
graphData.addRow(examname[i], {
v: highestScore[i],
f: userScore[i]
});
}
//graphData = graphData.replace(/'/g, '"');
//var data = google.visualization.arrayToDataTable(graphData);
console.log(data);
var options = {
title: 'Score Dashboard',
vAxis: {
title: 'Score'
},
hAxis: {
title: 'Exam Name'
},
seriesType: 'bars',
series: {
5: {
type: 'line'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(graphData, options);
}
JSFIDDLE
I am getting an error:
Error: If argument is given to addRow, it must be an array, or null
even I searched in google but I didn't understand. Please could any one help me to resolve the issue.
Your passing (string, object). When it's expecting just (array).
Change
graphData.addRow(examname[i], {
v: highestScore[i],
f: userScore[i]
});
To
graphData.addRow([
examname[i],
Number(highestScore[i]),
Number(userScore[i])
]);
Working example: https://jsfiddle.net/g4vjvam9/
Note: If you want the last column filled, you need to add the value :/
var userScore = ["6", "11", "2"];
Also avoid strings else your need to use Number() like above.

change event not working jquery autocomplete

Here is my function i wrote for getting usernames, location, and their pictures. Now the problem is if I use mustMatch option with it, every thing is working fine except for one bug. If lets say i type S it bring 'Sebastian' 'einstain'. If i select sebastian everything works like charm but if i select einstain it erases everything.
I tried to use change: event but its not firing in any case dont know why
$(document).ready(function(){
var wp_v = '3';
$("#searchbox").autocomplete("search.php?wp="+wp_v, {
matchContains: true,
//mustMatch: true,
width: 258,
scroll: true,
scrollHeight: 350,
dataType: 'json',
change: function (event, ui) {
alert('change');
if (!ui.item) {
$(this).val('');
}
},
parse: function(data) {
var array = new Array();
for (var i = 0; i < data.length; i++) {
array[array.length] = {
data: data[i],
value: data[i].name,
result: data[i].name
};
}
return array;
},
formatItem: function(row) {
var output = "<img class=img src='avatars/" + row.img + "'/> ";
output += "<span class=name>"+row.name+"</span><br/>";
output += "<span class=small>"+row.country+"</span><br/>";
return output;
}
}).result(function(event,item) {
if (item == undefined) {
$('#receiver').val('');
} else {
$('#receiver').val(item.uid);
}
});
});
This is the source
[
{"uid":"2","name":"Sebastian Aparicio","img":"1339875067-Koala.jpeg","country":"Leder"},
{"uid":"12","name":"Mester Jakob","img":"default.jpeg","country":"Salg"},
{"uid":"19","name":"Mester Jakob","img":"1339875047-Penguins.jpeg","country":"Leder"}
]
Actually autocomplete plugin version was different. That's why it was not working.

How to get slickgrid div to resize with size of table

I hope we have some users familiar with slickGrid seeing as how StackOverflow uses it also :)
I have a HTML containing my slickGrid as follows:
<div style="position:relative; overflow:visible; width:600px; margin:25px 0 0 0;">
<div id="myGrid" style="width:100%;overflow:visible; min-height:100px; max-height:300px;"></div>
</div>
<div class="options-panel">
<h2>Demonstrates:</h2>
<ul>
<li>adding basic keyboard navigation and editing</li>
<li>custom editors and validators</li>
<li>auto-edit settings</li>
</ul>
<h2>Options:</h2>
<button onclick="grid.setOptions({autoEdit:true})">Auto-edit ON</button>
<button onclick="grid.setOptions({autoEdit:false})">Auto-edit OFF</button>
</div>
<script type="text/javascript" language="javascript" src="./js/slickGrid/lib/firebugx.js"></script>
<!-- <script src="js/slickGrid/lib/jquery-1.7.min.js"></script>-->
<script src="js/slickGrid/lib/jquery-ui-1.8.16.custom.min.js.php"></script>
<script src="js/slickGrid/lib/jquery.event.drag-2.0.min.js"></script>
<script src="js/slickGrid/slick.core.js"></script>
<script src="js/slickGrid/plugins/slick.cellrangedecorator.js"></script>
<script src="js/slickGrid/plugins/slick.cellrangeselector.js"></script>
<script src="js/slickGrid/plugins/slick.cellselectionmodel.js"></script>
<script src="js/slickGrid/slick.formatters.js"></script>
<script src="js/slickGrid/slick.editors.js"></script>
<script src="js/slickGrid/slick.grid.js"></script>
<script>
function requiredFieldValidator(value) {
if (value == null || value == undefined || !value.length) {
return {valid: false, msg: "This is a required field"};
} else {
return {valid: true, msg: null};
}
}
var grid;
var data = [];
var columns = [
{id: "id", name: "Id", field: "id", width: 20, minWidth: 20, maxWidth:20, cssClass: "cell-title", editor: Slick.Editors.Text, validator: requiredFieldValidator, sortable: true},
{id: "date", name: "Date", field: "date", minWidth: 80, editor: Slick.Editors.Date, sortable: true},
{id: "venue", name: "Venue", field: "venue", width: 120, minWidth:120, editor: Slick.Editors.Text, sortable: true},
{id: "event", name: "Event", field: "event", width: 180, minWidth:180, editor: Slick.Editors.Text, sortable: true},
{id: "description", name: "Additional", field: "desc", width: 180, minWidth:180, editor: Slick.Editors.Text, sortable: true},
{id: "visible", name: "Visible", field: "visible", width: 20, minWidth: 20, cssClass: "cell-effort-driven", formatter: Slick.Formatters.Checkmark, editor: Slick.Editors.Checkbox, sortable: true}
];
var options = {
editable: true,
enableAddRow: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true,
multiColumnSort: true
};
$(function () {
for (var i = 0; i < 6; i++) {
var d = (data[i] = {});
d["id"] = i;
d["date"] = "06/31/2012";
d["venue"] = "Sample Venue";
d["event"] = "Sample Event";
d["desc"] = "$45 Door";
d["visible"] = (i % 5 == 0);
}
grid = new Slick.Grid("#myGrid", data, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onAddNewRow.subscribe(function (e, args) {
var item = args.item;
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
});
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
data.sort(function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
});
grid.invalidate();
grid.render();
});
})
</script>
<hr />EOP
What I want is for my slickGrid to gather data, then have the div automatically resize to encompass the updated grid. Currently it appears that the div size must be set statically? If I don't set values for the height of div "myGrid", it just sets it's height to 0. I want the div to expand with the size of the grid it loads.
The documentation for slickgrid on gitHub ( https://github.com/mleibman/SlickGrid/wiki/_pages ) is extremely limited (to be fair the author acknowledges this). I've also had a lot of trouble with this topic on google also.
I know it's software specific, but really hoping we have some slickGrid Guru's out there as this tool seems amazing!
You can use the autoHeight option to achieve this.
options = {
...
autoHeight: true
};
The containing div will expand to hold the entire grid avoiding the need for a scrollbar.
You can find an example here.
I suggest adding the following code to the onpagingInfoChanged
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
//......
///******************************************************
var divSize = 2 + (options.rowHeight * (pagingInfo.pageSize +1));
$("#myGrid").css( 'height' , divSize+'px' )
grid.resizeCanvas()
///*******************************************************
});
Being a bit lazy, I added the 2 px to the height to ensure the VScrollbar doesn't appear but I'm sure you can figure out something more pleasing.
Unfortunately, autoHeight and paging cannot be used together. If you want to use paging, you can auto-adjust the height of the table as follows (be sure to do this BEFORE rendering the data):
// Determine the total width of the grid div element
var gridWidth = 0;
for( i in columns )
{
if( columns[i].width != null && columns[i].width != 0 )
{
// Use the specified width
gridWidth += columns[i].width;
}
else
{
// If the column width is not specified, or is zero, try to use the default column width
if( columns[i].defaultColumnWidth == null ) // If default also does not exist
gridWidth += 80; // Pick an arbitrary default width (could replace with CSS property)
else
gridWidth += columns[i].defaultColumnWidth;
}
}
// Calculate the height of the Div by adding the values of the header row height and the row height * # rows
var rowH = (options.rowHeight != null ? options.rowHeight : 25); // If no rowHeight is specified, use the default size 25 (could be set by CSS)
var headerH = 0;
// First, determine whether to account for the header row
if( options.showHeaderRow == null || options.showHeaderRow == true )
{
// If so, use specified height, or default height
if( options.headerRowHeight == null )
headerH = 25;
else
headerH = options.headerRowHeight;
}
// Set the table size
var divSize = (json.length * rowH) + headerH + 1;
$j("#myGrid").css( 'height' , divSize+'px' )
.css( 'width' , gridWidth+'px' );

Categories