ChartJS sees date in string as numbers - javascript

I am trying to get some strings from a csv file, to put under a graph from chartjs.
I wrote this php function:
function getTitle($id) {
$stations = fopen("stations.csv", 'r');
//$csv_data = fopen(date("G") . '.csv', 'r');
$csv_data = fopen('16.csv', 'r'); //fopen("/mnt/weather-data/" .
date("Y/m/d/G") . ".csv", 'r');
$data = array();
$DAY_LENGTH = 60 * 60;
$currentDate = date('U');
while (($line = fgetcsv($csv_data)) !== FALSE) {
$date = date('U', strtotime($line[1]));
if ($date >= ($currentDate-$DAY_LENGTH) && $line[2] == $id) {
array_push($data, $line[0]);
}
}
for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . ",";
}
fclose($stations);
fclose($csv_data);
}
which is working fine, everywhere I call this function, it prints the necesarry strings, which is a date, so 2018-02-08 for example.
When I try to call this function in the label part where i need them in ChartJS. it returns this date as a sum, so like 2018-02-08 will return as 2008.
labels: [<?php getTitle(($_GET['id']))?>],
What is it what I'm doing wrong?
Another problem when I try to change $line[0] to $line[1] which is a time with the following format: 20:17:36, my whole application stops working..
Hope anyone can help me!!

The Problem with your code is that the echo will just output the content of the variable but as you are parsing it's value into a javascript array you need to surround your value with quotation marks. So if you change
for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . ",";
}
into
for ($i = 0; $i < count($data); $i++) {
echo "'" . $data[$i] . "',";
}
it should work. This will also solve your other problem. So with this change you should also be able to use the time.

Related

How to echo just few names of a list, in a clean way

I'm using the following code to list the first 7 names of a long list, for each post. The problem is when a certain post contains a list of names inferior to 7, for each missing name til 7, it automatically prints a comma ','
So when names are 7 or more, it correctly shows:
"name1, name2, name3, name4, name5, name6, name7"
While, if for example it contains just 3 names, it will print:
"name1, name2, name3,,,,"
Is there anyway to add something in the code to exclude printing commas in case of names minor to 7?
<?php
$value = get_post_meta($post->ID, 'list_of_names', true);
$value_array = explode(',', $value);
$hrefs = [];
for($i = 0; $i < 7; $i++)
{
$remove_space = str_replace(' ', '-', $value_array[$i]);
$url = esc_url('myblogurl' . $remove_space);
if ('' !== $url)
{
$display = esc_html($value_array[$i]);
$hrefs[] = "<a href='$url'>$display</a>";
}
}
echo implode(",", $hrefs);
?>
I've been trying to add elseif($i < 6) { echo ','; before the end, but it reported me a system error syntax :(
Any advice?
Limit your loop to the size of your $value_array, also maintaining the limit of 7.
for ($i = 0, $count = count($value_array); $i < 7 && $i < $count; $i++)
Another way of coding the same idea:
for ($i = 0, $min = min(7, count($value_array)); $i < $min; $i++)
You have the 'values' in an array, so you could use array functions.
<?php
$values = get_post_meta($post->ID, 'list_of_names', true);
$value_array = explode(',', $values);
$hrefs = [];
foreach (array_slice($value_array,0,7) as $value)
{
$remove_space = str_replace(' ', '-', $value);
$url = esc_url('myblogurl' . $remove_space);
if ('' !== $url)
{
$display = esc_html($value);
$hrefs[] = "<a href='$url'>$display</a>";
}
}
echo implode(",", $hrefs);
?>
See: array_slice()
I would advice to use something other than value as a variable name, if you want others to understand what your code is about.

Unix Timestamp Chart.js with PHP echo

I made a line chart with chart.js. For the values is some PHP script added. The axis only displayed the timestamp numbers. When I use a PHP function for timestamp conversion:
<?php echo date('H:i', $time); ?>
It totally crashes.
This is my code for the PHP time echo. How can I display HH:ii on my X axis of the chart?
<?php
$total = (count($data)) - 1;
if ($total > 100) {
$start = $total - 100;
$end = $total;
}
else {
$start = 0;
$end = $total;
}
for ($x = $start; $x < $end; $x++) {
if ($x % 5 == 0) {
//echo $x; //5th element
$row = $data[$x];
$time = intval($row->{'time'});
echo $time;
} else{
echo ' '; //prints empty for other than 5th element
}
echo ', '; //prints ',' for every element
Fixed it with:
echo '\'' . date('H:i', $time) . '\'';

jquery generate events over foreach

I'm programming appointment planer and still struggling with the issue that javascript doesn't generate events and prints the code just in plain text, so at first I have one php function which fetches all appointments from the sql database and generates javascript code
<script>
function getEventData() {
<?php
function showAppointments($von, $bis){
$link = OpenDB();
try {
$query = 'SELECT termin_id, client, dateFrom, dateTill, title, descri FROM termin WHERE dateFrom BETWEEN :von AND :bis';
$statement = $link->prepare($query);
$statement->bindValue(':von', $von, PDO::PARAM_STR);
$statement->bindValue(':bis', $bis, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetchAll();
}
catch (PDOException $e) {
p($e);
}
CloseDB($link);
return $row;
}
if(empty($von) && empty($bis)) {
$von = date("Y.m.j",strtotime("monday this week"));
$bis = date("Y.m.j",strtotime("sunday this week"));
}
if(isset($_POST['last_week'])){
$von = date("Y.m.j",strtotime("previous monday"));
$bis = date("Y.m.j",strtotime("previous sunday"));
}
if(isset($_POST['next_week'])){
$von = date("Y.m.j",strtotime("next monday"));
$bis = date("Y.m.j",strtotime("next sunday"));
}
$rows = showAppointments($von, $bis);
echo "const appointments = [";
for($i = 0; $i < sizeof($rows); $i++) {
$columns = array_values($rows[$i]);
echo "[";
for($j=0; $j< sizeof($columns); $j++){
echo "'".$columns[$j]."'";
if( $j < sizeof($columns)-1) echo ",";
}
echo "]";
if( $i < sizeof($rows)-1) echo ",";
}
echo "];";
?>
then all events are generated by jquery and returned
return {
events:[
$.each(appointments, function(index, row){
eval("{'id':"+ row[0] + ",'client':"+ row[1] +",'start':" + new Date(row[2])+",'end': "+ new Date(row[3]) +",'title':'"+ row[4] +"','description':'"+ row[5] +"'}");
});
]}}
</script>
the code in foreach is printed as plain text, how can I fix the issue? it should actually print something like
{'id':1, 'start': new Date(year, month, day, 12), 'end': new Date(year, month, day, 13, 30),'title':'Lunch with Mike'}
you should try the Jquery.each outside Events and then use eval(Array.join); in JavaScript, that should work

How to convert arrays from PHP/MySQL to Javascript

I am having difficulty with getting the JavaScript portion of this code to work the way I would like.
I have managed to pull the array from a MySQL table and convert it using JSON.
However, when I try to get the data into a HTML table, I get individual characters in each cell.
For example, my database has a table with a keyword labels. Inside this are 4 colors Blue, Green, Brown, Hazel exactly as I have entered it here.
When I output via JavaScript, I get one character in each cell instead of 4 cells.
I am "almost" there on my own:
<?php
include 'conn.php';
$sql = "SELECT * FROM variables WHERE id= '1' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$labels = $row["labels"];
}
foreach (explode(',', $labels) as $newLabel) {
echo "{$newLabel} ";
}
}
?>
<script>
<?php $newLabel = $labels ?>
var n = <?php print (json_encode($newLabel)); ?>;
var index;
var myTable= "<table class='hover'>";
myTable+= "<tr><td class='smalltd'style='width: 20px; font-weight:bold;'></td>";
for (index = 0; index < newLabel.length; index++) {
myTable+= "<td class='no' style='width: 100px; font-weight:bold;'>"
+ newLabel[index] + "</td>";
}
myTable+="</table>";
document.write(myTable);
</script>
I suspect the culprit lies in the newLabel.length but I am not certain
First of all, you need to collect your labels into an array, not a string:
$labels[] = $row["labels"];
Second, you've never defined the newLabel javascript variable.
Change
for (index = 0; index < newLabel.length; index++) {
to
for (index = 0; index < n.length; index++) {
and use n or rename n to newLabel

Grab two values in loop, check box and variable. Only grabbing checkbox? php w screenshot

i make a sql query asking for data(its a text question), i output the (question) with a checkbox to the left of it and an input field underneath it to give point worth to it(like a teacher making an exam) . All in a loop w arrays. It outputs the correctly checked questions but only will assign point values to first three questions if there checked. so if i check q1 q2 and q4 it will output q1 q2 q4 and q1 points q2points. Thats my problem, I only want to be able to select three total questions and assign those questions their points.
php in the html
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
im trying to output the data using this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i=1;
$total = 0;
while ($i < 4) {
$x = $i - 1;
echo $checkboxvar[$x];
echo $questionWorth[$x]."<br />";
$total = $total + $questionWorth[$x];
$i = $i +1;
}
echo $total;
As I told you in the comments try modifying your code like this:
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$i++.'-'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
And then, to have the right points for the correspondig question something like this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i = 0;
$total = 0;
while ($i < 3) {
$question = explode("-", $checkboxvar[$i]);
echo $question[1];
echo $questionWorth[$question[0]]."<br />";
$total += $questionWorth[$question[0]];
$i++;
}
echo $total;
This should do the work.
If i understand your implied question correctly, you will need some client side (javascript) code that keeps track of the number of checked checkboxes. As soon as one checks three boxes all remaining ones and corresponding text boxes are disabled.
for naive vanilla js solution your php could look like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["Question"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$index}'><br>";
$index++;
}
For modern browsers you would need the following in your javascript :
var selected_count = 0;
function limit_to_three(selected_checkbox) {
if (selected_checkbox.checked) {
selected_count++;
} else {
selected_count--;
}
var limit_reached = (selected_count == 3);
var checkboxes = document.getElementsByClassName('questions');
var scores = document.getElementsByClassName('scores');
for (var i=0; i<checkboxes.length; i++) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = scores[i].disabled = limit_reached;
}
}
}
Now, upon submit, you can assume that only checked question checkboxes will be submitted, so your php code could be like this:
$total = 0;
$length = strlen('questions_');
foreach ($_POST as $name => $value) {
if (substr($name, 0, $length) == 'questions_') {
$index = substr($name, $length - strlen($name));
echo $_POST[$name];
echo "<br>";
echo $_POST["scores_{$index}"];
$total += $_POST["scores_{$index}"];
}
}
As i said, this is a naive implementation, that sends question texts back and forth. If i were you i would add ID column to your questions table and use it instead of dynamically generated indexes
Then your html could be generated like this:
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["ID"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$row["ID"]}'><br>";
}
and your receiving php could be like this:
$checked = explode(',', $_POST['questions']);
for ($checked as $id) {
$total += $_POST["scores_{$id}"];
}
Also you could retrieve the checked questions by
$sql = "SELECT * FROM Questions WHERE ID IN ({$_POST['questions']})";

Categories

Resources