Google Charts - Labels not matching data - javascript

I am building a statistical view for a client's booking system. They'd like to see which activities were booked in specific months.
I'm using Google Charts for this but the data doesn't match the labels being produced - i.e. the correct data is being attached to the wrong activity.
I've verified via the database and print_r's that the product IDs are being pulled from the database successfully and attached to the correct activity ID number, and that the number and order of labels matches the number and order of activities, which they are:
$sql = "SELECT ProductID, ProductName FROM products ORDER BY ProductID ASC";
$set = $link->query($sql);
while($row = $set->fetch_row())
{
$arrLabels[$row[0]] = "#".$row[0].": ".$row[1];
}
ksort($arrLabels);
$sql = "SELECT * FROM bookings_products INNER JOIN bookings ON bookings.BookingID=bookings_products.BookingProductBooking WHERE BookingConfirmed>0 ORDER BY BookingProductProduct ASC";
$set = $link->query($sql);
while($row = $set->fetch_array(MYSQLI_ASSOC))
{
$dm = substr($row['BookingDate'],5,2); // To get the month from YYYY-MM-DD dates
$arrPeople[$dm][$row['BookingProductProduct']] = $arrPeople[$dm][$row['BookingProductProduct']] + (1 * $row['BookingGroupSize']);
}
ksort($arrPeople);
echo "<pre>"; print_r($arrLabels); echo "</pre>";
echo "<hr/>";
echo "<pre>"; print_r($arrPeople); echo "</pre>";
I then build the Google Charts JS code like this:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
[<?php foreach($arrLabels as $p) { ?>'<?php echo str_replace("'","\'",$p); ?>', <?php } ?>{ role: 'annotation' } ],
['Jan', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['01'][$k] ?: '0'; ?>, <?php } ?>],
['Feb', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['02'][$k] ?: '0'; ?>, <?php } ?>],
['Mar', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['03'][$k] ?: '0'; ?>, <?php } ?>],
['Apr', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['04'][$k] ?: '0'; ?>, <?php } ?>],
['May', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['05'][$k] ?: '0'; ?>, <?php } ?>],
['Jun', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['06'][$k] ?: '0'; ?>, <?php } ?>],
['Jul', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['07'][$k] ?: '0'; ?>, <?php } ?>],
['Aug', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['08'][$k] ?: '0'; ?>, <?php } ?>],
['Sep', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['09'][$k] ?: '0'; ?>, <?php } ?>],
['Oct', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['10'][$k] ?: '0'; ?>, <?php } ?>],
['Nov', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['11'][$k] ?: '0'; ?>, <?php } ?>],
['Dec', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['12'][$k] ?: '0'; ?>, <?php } ?>],
]);
var options = {
title: 'Product popularity by month - Number of people (based on activity date)',
isStacked: true,
};
var chart = new google.visualization.BarChart(document.getElementById('chart3b'));
chart.draw(data, options);
}
</script>
<div id="chart3b" style="margin-top:15px; width: 900px; height: 500px; border:solid 1px #000;"></div><hr/>
You can see (via a static HTML copy-and-paste of the dynamic PHP output) the Google Chart produced here: http://www.stuart-pinfold.co.uk/stats.htm
You'll notice that activity #50 (Santa Experience) which had 195 visitors in December (month 12) is being assigned in the chart to activity #51 ("Zombie Air Rifle, Zombie Pistol, 10 Clay Shoots") instead.
Where am I going wrong?

Your first column of values is the month name, but your first cell at your headers row isn't a "month" label.
If you look at your example the activity #50 (Santa experience), you can see that the value of this label is 1 step to the left in the graph.
Make sure that instead of
['#5: Special Offer Ultimate Shooting Package ', '#6: CPSA Shotgun Skills Course',.....],
['Jan', 0,....
it looks like
['Months', '#5: Special Offer Ultimate Shooting Package ',.....],
['Jan', 0,.....
and everything should work just fine.

Related

extract all js scripts and style from HTML and add to textarea

I written code below that will extract the js like this:
src="assets/js/jquery.min.js"
src="assets/smooth-scroll/smooth-scroll.js"
I would like to have it like: (I guess my regex is wrong):
<script src="assets/js/jquery.min.js"></script>
<script src="assets/smooth-scroll/smooth-scroll.js"></script>
Here is my code:
$htmlData = file_get_contents($url);
if ($htmlData === false) {
echo "error!!";// Handle the error
die();
}
preg_match_all("/\<script(.*?)?\>(.|\\n)*?\<\/script\>/i", $htmlData, $matches);
//example output #1
echo "<pre>";
echo print_r($matches[1]);
echo "</pre>";
//example output #2
$matches = $matches[1];
foreach ($matches as $val) {
//echo "<script";
echo $val;
//echo "</script>"; //<-- adding <script> tags breaks this code
}
So how would I add all scripts into a textarea from this point?
Not sure the regex for styles to do the same.
You need to include the script part in the captured segment.
preg_match_all("/(\<script(.*?)?\>(?:.|\\n)*?\<\/script\>)/i", $htmlData, $matches);
Ok I figured out my code:
$htmlData = file_get_contents($wurl);
if ($htmlData === false) {
echo "error!!";// Handle the error
die();
}
preg_match_all("/(\<script(.*?)?\>(?:.|\\n)*?\<\/script\>)/i", $htmlData, $scripts);
preg_match_all('/<link(.*?)?\>/is', $htmlData, $styles);
//$scripts.=implode(" ",$matches[2]);
//Print array for scripts to get array level;
echo "<pre>";
print_r($scripts[2]);
echo "</pre>";
//Print array for styles to get array level;
echo "<pre>";
print_r($styles[1]);
echo "</pre>";
$scripts = $scripts[2];
foreach ($scripts as $script) {
$all_scripts.= "%script ".$script."#%/scripts#"."\n";
}
$styles = $styles[1];
foreach ($styles as $style) {
$all_styles.= "%link ".$style."#"."\n";
}
$all_scripts = str_replace(array('%', '#'), array(htmlentities('<'), htmlentities('>')), $all_scripts);
$all_styles = str_replace(array('%', '#'), array(htmlentities('<'), htmlentities('>')), $all_styles);
echo "<p>My Scripts:<br/>";
echo $all_scripts;
echo "</p>";
echo "<p>My Styles:<br/>";
echo $all_styles;
echo "</p>";
?>
<textarea name="my_Styles" rows="8" cols="100">
<?php echo $all_styles; ?>
</textarea>
<textarea name="my_Scripts"rows="8" cols="100">
<?php echo $all_scripts; ?>
</textarea>

Google charts numbers

i use a google charts for getting data from google analytics to see it in my website
there is some data have a decimal number
how to make the charts forgot the number after the decimal.
I use a php foreach in the data generate for the charts
like this:
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } ],
<? foreach($SOMETHING->getRows() as $row) {
$test = $row[2];
$test = number_format($test,0);?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo $test; ?> ],
<? }?>
]);
i try the php coding "number_format" but it working in the script if i see the inspect of the page but not showing any charts in the page
if i put this code it work but the decimal is still there
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } ],
<? foreach($tristanweekdata->getRows() as $row) { ?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo $row[2]; ?> ],
<? }?>
]);
P.S.: this code is for one of my charts but its effect all the charts and all of them not showing anything
what should i do for remove the decimal????
thanks
Wrap your value in PHP's floor or intval method: (using number_format as you have it will add commas at the thousandths place in your numbers, so that should be avoided).
echo floor(456.8)."<br/>";
echo floor(456)."<br/>";
echo floor(456.1)."<br/>";
echo floor(456.0);
// outputs:
// 456
// 456
// 456
// 456
echo intval(456.8)."<br/>";
echo intval(456)."<br/>";
echo intval(456.1)."<br/>";
echo intval(456.0);
// outputs:
// 456
// 456
// 456
// 456
So in your example above:
$test = floor($row[2]);
//or
$test = intval($row[2]);
Floor:
Returns the next lowest integer value
http://php.net/manual/en/function.floor.php
Intval
Returns the integer value of var, using the specified base for the conversion (the default is base 10)
http://php.net/manual/en/function.intval.php

Empty jQuery Autocomplete Array in Firefox and Chrome - Works in Safari

My php invoicing system uses jQuery autocomplete to lookup a customer's name from my database. The layout of the pages is like this:
invoice.php - contains the variable 'customers' and the php database select script
invoice.js - this contains the jQuery on focus command
In Safari everything works fine. I have used the console to see the variables logged - example (CUSTOMERS – ["Paul Smith"] (1))
But in Chrome and Firefox the console shows: "CUSTOMERS" Array [ ]
My code for invoice.php:
var arr_customers = new Array();
<?php $result = mysql_query("select * from customer where breaker='".$_SESSION['breaker_id']."'");?>
<?php $str = ""; $i = 0; while ($row = mysql_fetch_array($result)) { ?>
arr_customers[<?php echo $i;?>] = new Array();
arr_customers[<?php echo $i;?>][0] = "<?php echo $row['customer_name']; ?>";
arr_customers[<?php echo $i;?>][1] = "<?php echo $row['customer_code']; ?>";
arr_customers[<?php echo $i;?>][2] = "<?php echo $row['address']; ?>";
arr_customers[<?php echo $i;?>][3] = "<?php echo $row['uid']; ?>";
<?php if ($i == 0) {
$str = "'" . $row['customer_name'] . "'";
} else {
$str = $str . ",'" . $row['customer_name'] . "'";
}?>
<?php $i++;
} ?>
var customers =<?php echo ("[" . $str . "]") ?>;
and for the invoice.js:
jQuery(document).ready(function($) {
$("#customer_name").on('focus', function() {
console.log("CUSTOMERS", customers);
$( "#customer_name" ).autocomplete({
source: customers
});
});
});
I know I should be using prepared statements as well!

Use PHP variable in Java Script contained within HTML

I would like to use PHP variable in Java Script, I would like to get the variables of longitude and latitude which is returned from Select statement read from mysql database on the server.
here with my code below and what I have tried:
<?php
...
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Latitude, Longitude FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$long = " ". $row["Longitude"]. "<br>";
$lat = " ". $row["Latitude"]. "<br>";
$latlong = " ". $row["Longitude"]. " , " . $row["Latitude"]. "<br>";
echo $long; //echo's -25.1234
echo $lat; //echo's 25.1234
echo $latlong; //echo's -25.1234 , 25.1234
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Tracker</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 1200px; height: 750px;"></div>
<script language="JavaScript">
var locations = [
['FirstColumnString<br/> SecondColumnString', -25.038326, 25.038326], //I would like to pass Lat Long from PHP code from above
];
// I've tried
// ['FirstColumnString<br/>SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>,
// ['FirstColumnString<br/>SecondColumnString', <?php echo $latlong ?>,
// ['FirstColumnString<br/>SecondColumnString', "<?php echo $long; ?>", <?php echo $lat; ?>,
...
</script>
</body>
</html>
You should save your locations into an array first:
<?php
$locations = Array();
while($row = $result->fetch_assoc()) {
$loc = Array("lat" => $row["Latitude"], "long" => $row["Longitude"]);
$locations[] = $loc;
}
?>
then you can pass it to javascript:
<script>
var locations = <?php echo json_encode($locations) ?>;
// check what you've got:
console.log(locations);
</script>
you could then access your values like this:
var firstLocationLatitude = location[0].lat;
If you need to have your js-array exactly as you've posted change php to:
$clmString = "FirstColumnString<br/> SecondColumnString";
while($row = $result->fetch_assoc()) {
$loc = Array($clmString,$row["Latitude"],$row["Longitude"]);
$locations[] = $loc;
}
Try replacing
$long = " ". $row["Longitude"]. "<br>";
$lat = " ". $row["Latitude"]. "<br>";
with
$long = $row["Longitude"];
$lat = $row["Latitude"];
and then
var locations = [
['FirstColumnString<br/> SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>],
];

Javascript/jQuery Loop

I have a bit of jQuery that animates in some text then animates it out. The parameters of the animation are passed via PHP. I need the animation to loop but only after the animation is complete, but can't quite work it out.
<?php if ($text1_1 != "") { ?>
setTimeout(one_1,0); // From 0 to duration
setTimeout(one_2,<?php echo $duration * 2 ?>);
// From duration x2 to duration x3
<?php } ?>
<?php if ($text2_1 != "") { ?>
setTimeout(two_1,<?php echo $duration * 3 ?>); // From duration x3 to duration x4
setTimeout(two_2,<?php echo $duration * 5 ?>); // From duration x5 to duration x6
<?php } ?>
<?php if ($text1_1 != "") { ?>
function one_1() {
$('.text-1_1').animate({ <?php echo $animate1_1 ?>: '<?php echo $text1_1_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_2').animate({ <?php echo $animate1_2 ?>: '<?php echo $text1_2_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_3').animate({ <?php echo $animate1_3 ?>: '<?php echo $text1_3_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_4').animate({ <?php echo $animate1_4 ?>: '<?php echo $text1_4_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_5').animate({ <?php echo $animate1_5 ?>: '<?php echo $text1_5_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
}
function one_2() {
$('.text-1_1').animate({ <?php echo $animate1_1 ?>: '<?php echo $text1_1_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_2').animate({ <?php echo $animate1_2 ?>: '<?php echo $text1_2_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_3').animate({ <?php echo $animate1_3 ?>: '<?php echo $text1_3_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_4').animate({ <?php echo $animate1_4 ?>: '<?php echo $text1_4_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_5').animate({ <?php echo $animate1_5 ?>: '<?php echo $text1_5_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
}
<?php } ?>
How would you get function one_1() & function one_2() to loop after they've finished animating. There is also the possibility that there will be more similar functions.
Very sorry if this is a bit vague! having a bit of trouble explaining it.
Thanks for looking!
You can use the animate finish callback as described here:
http://api.jquery.com/animate/
$(element).animate( { animation params }, duration, function(){
// this is the animation finish callback
});
My suggestion is to use a recursive function, put the animation inside and call it recursively when the animation is finished
You could use something like this as a template. If the durations within each group are not the same, will require considerably more logic to set up and you would likely be best to provide all the animation data as an array, not echo to each animation
function one_1() {
/* use complete callback of one animation to call next function*/
$('.text-1_5').animate({ /* anim*/}, /*duration*/, /* easing*/, function(){
/* this animation is complete, call next function */
two_1();
});
/* other animations for this group*/
}
Maybe the solution is to replace setTimeout with
setInterval(two_1,<?php echo $duration; ?>);
setInterval(two_2,<?php echo $duration; ?>);
There is now need for doing $duration * 3 because your animations will start all in the same time

Categories