Data from PHP to JS - Google calendar + CanvasJS - javascript

I want to get data from Google calendar to make Chart how much you are at work.
My problem is that i cant load data from PHP to JS -> $DataJSON cant be load by JS...Final script should count how many hours you spend at meetings etc.. There is code
<?php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->addScope("https://www.googleapis.com/auth/calendar");
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
?>
<form action="" method="POST" enctype="multipart/form-data">
<?php
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo '<input type="checkbox" value='.$calendarListEntry->id.' name="zasedacky[]">' .$calendarListEntry->getSummary()."</br>";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
<select name="type">
<option value="column">Column</option>
<option value="bar">Bar</option>
<option value="area">Area</option>
</select>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$type = $_POST['type'];
$zst = $_POST['zasedacky'];
if(empty($zst))
{
echo("Nevybrali jste žádnou zasedací místnost.");
}
else
{
$N = count($zst);
$data_points = array();
for($i=0; $i < $N; $i++)
{
$calendar = $service->calendars->get($zst[$i]);
$calendarJSON = array("label" => $calendar->getSummary(), "y" => "11");
array_push($data_points, $calendarJSON);
}
$dataJSON = json_encode($data_points, JSON_NUMERIC_CHECK);
echo $dataJSON;
}
}
?>
<script>
$(document).ready(function () {
var dataPoints = <?=$dataJSON ?>;
for(var i = 0; i <= result.length-1; i++)
{
dataPoints.push({label: result[i].label, y: parseInt(result[i].y)});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
document.write(dataPoints);
});
</script>
</body>
<?php
} else {
$redirect_uri = 'http://localhost/calendar/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Thanks for your help

It seems you forgot to define the result variable. Maybe you intended to do this:
<script>
$(document).ready(function () {
var result = <?=$dataJSON ?>;
var dataPoints = [];
for(var i = 0; i <= result.length-1; i++)
{
dataPoints.push({label: result[i].label, y: parseInt(result[i].y)});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
</script>
Hardcoded data format you provided seems to work fine. Here is the JSFiddle

Related

check duplicate rand function value in database and generate it again

i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.

create chart with oracle query

i am trying to create a chart pie with a query from oracle database.
i have already connect to the data base and echo the results,but i cant create a chart.any suggestion about this?
<?php
$tns = "
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = xxx.xxxx.xxx.xxx)(PORT = xxxx))
)
(CONNECT_DATA =
(SERVICE_NAME = XE)
)
)
";
$db_username = "xxx";
$db_password = "xxxxR";
try{
$conn = new PDO("oci:xxxx=".$tns,$db_username,$db_password);
}catch(PDOException $e){
echo ($e->getMessage());
}
if (!$conn) {
$m = oci_error();
echo $m['message'], "\n";
exit;
}
else {
echo "Connected to Oracle!";
}
$query = "SELECT T71.C_C1003000015, COUNT (T71.C1)
FROM ICT_DATABASE.T71 T71
WHERE (T71.C_C1003000015 NOT IN (exelllllllllxx.xxxx.xxx'))
AND trunc(T71.ARRIVAL_DATE) = trunc(sysdate)
GROUP BY T71.C_C1003000015";
$stmt = $conn->prepare($query);
if ($stmt->execute()) {
echo "<h4>$query</h4>";
echo "<pre>";
while ($row = $stmt->fetch()) {
print_r($row);
}
echo "</pre>";
}
?>
that code is working and export data how can i create a chart now?
ok, here goes.
you need to add Google's scripts to your page.
<script src="https://www.google.com/jsapi"></script>
Add this div where you want the chart...
<div id="piechart" style="width: 900px; height: 500px;"></div>
then add this JavaScript, assuming you leave the output in the <pre> element
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var googleArray = [];
googleArray.push(['Department', 'Value']);
var testRow = document.getElementsByTagName('PRE')[0].innerHTML;
var testArr = testRow.split('IT-EXT-COSMOTE-');
var deptSplit;
for (var i = 0; i < testArr.length; i++) {
if (testArr[i] !== '') {
deptSplit = testArr[i].split(' - ');
googleArray.push([deptSplit[0], Number(deptSplit[1])]);
}
}
var dataTable = new google.visualization.arrayToDataTable(googleArray, false);
var chartOptions = {title: 'Department Totals'};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(dataTable, chartOptions);
}
let me know if you need further help...

PHP Page: Dropdown always selects the first value

I have multiple dropdown lists on my PHP page and all are created like this:
<?php
//Select values from MySQL Database
$query = "SELECT name FROM Player";
$result = mysql_query($query);
//Show DropDownList
echo '<select name="players" onclick="sortlist(this)">';
while($row = mysql_fetch_assoc( $result ))
{
echo '<option value="'.$row['name'].'">' . $row['name'] . '</option>';
}
echo '</select>';
?>
Now in case you haven't noticed I call a javascript function "sortlist(this)" on every dropdownlist i have. This function just order values alphabetically. You can check the script:
<script>
function sortlist(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
</script>
All my dropdownlists are inside a form tag like this:
<form accept-charset="utf-8" action="" method="post">
The script is running ok, i have the dropdownlist ordered alphabetically, but whenever i select one value, it always shows the first one.
try something like this
<body>
<select id="select_id" >
<option value="B">B</option>
<option value="Z">Z</option>
<option value="C">C</option>
<option value="E">E</option>
<option value="A">A</option>
</select>
</body>
<script type="text/javascript">
function sortlist(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
sortlist(document.getElementById('select_id'));
</script>
REASON: your script always sorting your select on onclick no matter whether you are selecting value it is sorting and reseting your selected value.
so call your script only once for sorting after you have render your select element
Why not just
$query = "SELECT name FROM Player ORDER BY name ASC";
How about this
function sortlist(elem) {
arrTexts = new Array();
for(i=0; i<elem.length; i++) {
arrTexts[i] = elem.options[i].text;
}
arrTexts.sort();
for(i=0; i<elem.length; i++) {
elem.options[i].text = arrTexts[i];
elem.options[i].value = arrTexts[i];
}
}

Magento Images switcher for custom options

I have created a custom options image switcher for Magento, script compares value from options in drop-down with all image names related to product, and finds the most similar one, you can see an example here
The problem is how to add the "selected" option image to the cart, or better to say how to apply that image instead of the default thumbnail in the cart?
anyway here is the complete code - maybe someone can even find this part useful :)
<?php
// load all images related to product
$product = $this->getProduct();
$galleryData = $product->getData('media_gallery');
$images_array = array();
foreach ($galleryData['images'] as $image) {
array_push($images_array, $image['file']);
}?>
<?php
$colour_select_id = '';
$custom_options_arr = array();
foreach ($_options as $_option) {
if ($_option->getTitle() == 'Helmet Color/Design' || $_option->getTitle() == 'Color') {
$colour_select_id = 'select_' . $_option->getId();
$values = $_option->getValues();
foreach ($values as $value) {
$current_option = ($value->getData());
$custom_options_arr[$current_option['option_type_id']] = $current_option['title'];
}
}
}
// $custom_options_arr now holds key=>value pairs of option_type_id => title
$custom_images_to_output = array();
foreach ($custom_options_arr as $key => $value) {
$best_match = $images_array[0];
for ($i = 1; $i < count($images_array); $i++) {
if (similar_text(strtoupper($images_array[$i]), strtoupper($value)) > similar_text(strtoupper($best_match), strtoupper($value))) {
$best_match = $images_array[$i];
}
}
$custom_images_to_output[$key] = $best_match;
}
$base_url = Mage::getBaseUrl('media') . 'catalog/product';
?>
<?php if ($colour_select_id) { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
var opt_object = <?php echo json_encode($custom_images_to_output); ?>;
var base_path = '<?= $base_url;?>';
jQuery("#<?= $colour_select_id ?>").change(function() {
var optionValue = jQuery(this).attr('value');
if (optionValue) {
var optionValueText = jQuery.trim(jQuery('#<?= $colour_select_id ?> :selected').text());
if (opt_object.hasOwnProperty(optionValue)) {
optionValueText = opt_object[optionValue];
}
jQuery("#image").fadeOut(function() {
jQuery(this).load(function() {
jQuery(this).fadeIn(); });
jQuery(this).attr("src", base_path + optionValueText);
jQuery('#image-zoom').attr("href", base_path + optionValueText);
});
}
});
});
</script>

PHP post variable is not being rendered

I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>

Categories

Resources