I try to make availability calendar with FullCalendar.js. Everything works fine if I call events from database in my index.php, but when I try to get events via json I get nothing. Calendar is showing but normally, but not showing events. When I look in smjestaj-rezervacija-kalendar.php I get:
[ { title: 'Rezervirano', start: '2015-01-30', allDay: true } , { title: 'Rezervirano', start: '2015-01-31', allDay: true } , { title: 'Rezervirano', start: '2015-02-01', allDay: true } ]
so it works. Anyone having idea why it doesn't show on calendar, what am I doing wrong?
index.php
<script type="text/javascript">
$(document).ready(function(){
// Event calendar js
try{
$('#utopia-fullcalendar-2').fullCalendar({
header:{
left:'prev,next',
center:'title',
right:''
},
dayNames: ['Nedjelja','Ponedjeljak','Utorak','Srijeda','Četvrtak','Petak','Subota'],
dayNamesShort: ['Ned','Pon','Uto','Sri','Čet','Pet','Sub'],
monthNames: ['Siječanj','Veljača','Ožujak','Travanj','Svibanj','Lipanj','Srpanj','Kolovoz','Rujan','Listopad','Studeni','Prosinac'],
monthNamesShort: ['Sij','Velj','Ožu','Tra','Svi','Lip','Srp','Kol','Ruj','Lis','Stu','Pro'],
firstDay:1,
editable:false,
height:540,
events: 'smjestaj-rezervacija-kalendar.php?SmjestajID=<?=$_GET['SmjestajID'];?>'
});
} catch (e){
errorMessage(e);
}
});
</script>
and here is my smjestaj-rezervacija-kalendar.php:
<?php
header('Content-type: text/json; charset=utf-8');
include($_SERVER['DOCUMENT_ROOT']."/admin/config.php");
echo '[';
$SmjestajID = $_GET['SmjestajID'];
$rezultat_kalendar = mysqli_query($link, "SELECT * FROM smjestaj_kalendar WHERE KalendarSmjestaj=$SmjestajID ORDER BY KalendarID ASC");
$broj_unosa = mysqli_num_rows($rezultat_kalendar);
$i = 1;
while ($redak_kalendar = mysqli_fetch_array($rezultat_kalendar))
{ ?> {
title: 'Rezervirano',
start: '<?=$redak_kalendar['KalendarDatum']?>',
allDay: true
}
<?php
if ($i <> $broj_unosa){
echo ',';
}
$i ++;
}
echo ']';
?>
I try with http://fajitanachos.com/Fullcalendar-and-recurring-events/ json file, but still get nothing.
I googled and find that in json should be no html object, so I remove header('Content-type: text/json; charset=utf-8'); and go with array instead of html. This answer was helpfull: How do I get FullCalendar to display information from my JSON feed?
<?php
include($_SERVER['DOCUMENT_ROOT']."/admin/config.php");
$SmjestajID = $_GET['SmjestajID'];
$rezultat_kalendar = mysqli_query($link, "SELECT * FROM smjestaj_kalendar WHERE KalendarSmjestaj=$SmjestajID ORDER BY KalendarID ASC");
while ($record = mysqli_fetch_array($rezultat_kalendar)) {
$event_array[] = array(
'id' => $record['KalendarID'],
'title' => "Rezervirano",
'start' => $record['KalendarDatum'],
'allDay' => true
);
}
echo json_encode($event_array);
?>
Related
I'm trying to fetch data from DB for a line graph using the below code.
<?php
$dataPoints = array(
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
array("y" => 25, "label" => "Sunday"), ?>
} } else { }
);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line
However if i m to remove the sql query, graph plots with static data perfectly.
Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.
<?php
// import your mysqli connection before
$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.
$dataPoints = array();
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$dataPoints[] = $row;
}
}
I'm trying to display a highstock candlestick chart, but I can't achieve it.
My website shows a blank where the chart should be, but there's nothing showing in the chart.
How can I fix it to show the chart?
I have two scripts:
datachart.inc.php:
<?php
include '../dbh.php'; //It connects to the database
$sql = "SELECT * from table";
$result = $conn->query($sql);
$row = mysqli_fetch_array($result);
$data = array();
$count = 0;
while ($row=mysql_fetch_array($result))
{
$newdate = strtotime($row['date']) * 1000;
$data[] = array($newdate, (float)$row['open'], (float)$row['high'],
(float)$row['low'], (float)$row['close']);
$count++;
}
echo json_encode($data);
?>
index.htm:
<!DOCTYPE HTML>
<HTML>
<BODY>
<script>
$(function() {
$.getJSON('datachart.inc.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
},
rangeSelector : {
selected : 1
},
title : {
text : 'Test Price'
},
series : [{
type : 'candlestick',
name : '',
data : data,
tooltip: {
valueDecimals: 2
},
dataGrouping : {
units : [
['week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]]
]
}
}]
});
});
});
</script>
<div id="container" style="height: 250px; min-width: 250px"></div>
</BODY>
</HTML>
Click here to see a picture of my sql table
Solved:
1) Import the javascript files
2) Remove "$row = mysqli_fetch_array($result);"
3) Change "while ($row=mysql_fetch_array($result))" to "while ($row=mysqli_fetch_array($result))"
I am trying to select data based on a value, I have a form which selects data from a table of teams, I need to to get the ID of that row from the select dropdown (which I can do) but then use that to determine the data that it needs to select when im doing an AJAX request. Here goes:
Teams page - This page draws my graph which pulls in data via AJAX to draw the graph and its values:
<form action="teams.php?dashboard_id=<?php echo $dashboard_id; ?>" method="POST">
<select name="teamId">
<option selected="true" disabled="disabled">Please choose...</option>
<?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboard_id";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value=' . $row["team_id"] . '>' . $row["team_name"] . '</option>';
}
}
?>
</select>
<button class="compare">View</button>
</form>
<?php
if (!empty($_POST["teamId"])) {
$teamSelect = $_POST["teamId"];
echo $teamSelect;
}else{
echo "";
}
?>
<div style="max-width: 450px;">
<canvas id="mycanvas" class="container"></canvas>
</div>
Here is the PHP page that im doing the SELECT on:
<?php
include 'config.php';
$teamID = $_POST['teamId'];
$query = sprintf("SELECT
tm.member_id,
tm.team_id,
m.member_id,
m.firstName,
m.lastName,
m.score_1,
m.score_2,
m.score_3,
m.score_4,
m.score_5,
m.score_6,
m.score_7,
m.score_8,
m.dashboard_id,
t.team_id,
t.team_name,
t.dashboard_id
FROM team_members tm
JOIN members AS m
on m.member_id = tm.member_id
JOIN teams AS t
on t.team_id = tm.team_id
WHERE tm.team_id = '$teamID'"); // This need to be dynamic and got from the POST request on the form above.
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
header('Content-type: application/json');
print json_encode($data);
?>
Im drawing the graph out via another file:
$(document).ready(function(){
$.ajax({
url : "http://localhost/acredashAdv/teamData.php",
type : "GET",
success :function(data){
console.log(data);
var chartata = {
labels: [
"Strategic Development and Ownership",
"Driving change through others",
"Exec Disposition",
"Commercial Acumen",
"Develops High Performance Teams",
"Innovation and risk taking",
"Global Leadership",
"Industry Leader"
]};
var ctx = $("#mycanvas");
var config = {
type: 'radar',
data: chartata,
animationEasing: 'linear',
options: {
legend: {
display: true,
position: 'bottom'
},
tooltips: {
enabled: true
},
scale: {
ticks: {
fontSize: 15,
beginAtZero: true,
stepSize: 1
}
}
},
},
LineGraph = new Chart(ctx, config);
var colorArray = [
["#7149a5", false],
["#58b7e0", false],
["#36bfbf", false],
["#69bd45", false],
["#5481B1", false],
["#6168AC", false]
];
for (var i in data) {
tmpscore=[];
tmpscore.push(data[i].score_1);
tmpscore.push(data[i].score_2);
tmpscore.push(data[i].score_3);
tmpscore.push(data[i].score_4);
tmpscore.push(data[i].score_5);
tmpscore.push(data[i].score_6);
tmpscore.push(data[i].score_7);
tmpscore.push(data[i].score_8);
var color, done = false;
while (!done) {
var test = colorArray[parseInt(Math.random() * 6)];
if (!test[1]) {
color = test[0];
colorArray[colorArray.indexOf(test)][1] = true;
done = !done;
}
}
newDataset = {
label: data[i].firstName+' '+data[i].lastName,
borderColor: color,
backgroundColor: "rgba(0,0,0,0)",
data: tmpscore,
};
config.data.datasets.push(newDataset);
}
LineGraph.update();
},
});
});
This is all great but in my select query I need the WHERE clause to show me data determined on the value of the team ID and not a static value but im not sure how to pass across the ID from the select back to the AJAX file?
Use sessions then. $_SESSION['teamID'] = $teamID. Then you can reference it anywhere. Be sure to start the session at the top of each php file using sessions.
session_start();
$teamID = $_POST['teamId'];
$_SESSION['teamID'] = $teamID;
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/book.session.php
EDIT
Is it possible to send the json data into this part:
$.each( res, function(key, row)(
{
events: [
{
title: 'All Day Event',
start: //from AJAX row['name'],
backgroundColor: "#f56954", //red
borderColor: "#f56954" //red
},
...
I am trying to add data from MysQL into fullcalendar.
Here is my fullcalendar script:
<script>
(function ($) {
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: {
url: 'fullcalendar/get-events.php',
//url: 'fullcalendar/myfeed.php',
error: function() {
$('#script-warning').show();
}
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
})(jQuery);
</script>
Where I get values from get-events.php, and here is the code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('global.php');
//Json and PHP header
header('Content-Type: application/json');
$events = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
$search_date = "SELECT * FROM appointment WHERE id_logged = :id_logged";
$search_date_stmt = $conn->prepare($search_date);
$search_date_stmt->bindValue(':id_logged', $id_logged);
$search_date_stmt->execute();
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
$i = 0;
foreach($search_date_stmt_fetch as $row)
{
$events[$i] = $row;
$i++;
}
echo json_encode($events);
?>
The result is show properly at the XHR:
But I can't see any of them in the calendar:
Build your response like the doc said :
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
foreach($search_date_stmt_fetch as $row)
{
$events[] = array(
'start' => $row->your_date_start,
'end' => $row->your_date_end,
'id' => $row->your_id
...);
}
echo json_encode($events);
See the doc to know the properties you need : http://fullcalendar.io/docs/event_data/Event_Object/
I am grateful in advance of any help I receive on this. I also apologise if my error is obvious. My problem is I can't seem to find an idea on how to display all the elements of my array to populate my events.
for(var i = 0;i < count;i++)
{
// these are the arrays that contain my events
var primaryAsset = primaryAssets[i];
var release_Date = releaseDates[i];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
weekMode: 'liquid',
weekends: true,
events: [
{
title: primaryAsset,
start: release_Date,
end: release_Date
}
]
});
}
Please create event array first then pass into full calender like
var evt = [
{
title : 'event1',
start : '2014-01-01'
},
{
title : 'event2',
start : '2014-01-05',
end : '2014-01-07'
},
{
title : 'event3',
start : '2014-01-09T12:30:00',
allDay : false
}
];
then add into full calender
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
weekMode: 'liquid',
weekends: true,
events: evt
});
This my script to get json data from php file. thats may works for you.
<script>
$('#calendar').fullCalendar(
{
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events:
{ // Render the events in the calendar
url: 'calendarData.php', // Get the URL of the json feed
error: function()
{
alert('There Was An Error While Fetching Events Or The Events Are Not Found!');
}
}
});
</script>
calendarData.php
$return_array = array();
while ($row = mysql_fetch_array($sth))
{
$event_array = array();
$event_array['id'] = $row['e_id'];
$date_start = $row['e_date_start'];
$date_end = $row['e_date_end'];
$date_start = explode(" ",$date_start);
$date_end = explode(" ", $date_end);
$date_start[0] = str_replace('-' , '/' , trim($date_start[0]));
$date_end[0] = str_replace('-' , '/' , trim($date_end[0]));
//Event Title Structure
if($row['e_title'] != "")
{
$event_array['title'] = $row['e_title'];
//Start Date Structure
if($date_start[0] != "0000/00/00" && $date_start[1] != "00:00:00")
{
$event_array['start'] = date(DATE_ISO8601, strtotime($date_start[0]." ".$date_start[1]));
}
//End Date Structure
if($date_end[0] != "0000/00/00" && $date_end[1] != "00:00:00")
{
$event_array['end'] = date(DATE_ISO8601, strtotime($date_end[0]." ".$date_end[1]));
}
//All Day Event Structure
if($row['e_allday'] == '1')
{
$event_array['allDay'] = true;
}
elseif($row['e_allday'] == '0')
{
$event_array['allDay'] = false;
}
array_push($return_array, $event_array);
}
}
echo json_encode($return_array);
Here are the steps that I took, which worked pretty slick:
1. Load the calendar, using the basic code in fullCalendar documentation:
<script>
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
// put your options and callbacks here
})
});
</script>
make sure you can actually pull in the data from your array (it doesn't need to be in the calendar yet, just load it onto the page to verify that it works). Something like this should do it: (note, I have not tested this code, but it is close. May need to be tweeked though)
if ( have_posts() ) :
//start a while statement
while ( have_posts() ) :
the_post();
$content_types = get_the_terms( $post_id, $taxonomy_categories );
$tag_link = get_field('tag_link');
$tag_host = parse_url($tag_link);
$tag_page = $tag_host['scheme'] . '://' . $tag_host['host'];
echo the_title();
echo the_field('date');
endwhile;
endif;
add static array, to test if the array elements will be displayed on the calendar. Use code from fullCalendar documentation:
$('#calendar').fullCalendar({
events: [
{
title : 'event1',
start : '2010-01-01'
},
{
title : 'event2',
start : '2010-01-05',
end : '2010-01-07'
},
{
title : 'event3',
start : '2010-01-09T12:30:00',
allDay : false // will make the time show
}
]
});
Finally, once everything to this point is working, replace the static data with dynamic data. You can do this by wrapping it with a loop, and getting the necessary fields through php. Here is the code that I used:
<script>
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
// put your options and callbacks here
events: [
//start if
<?php
if ( have_posts() ) :
//start a while statement
while ( have_posts() ) :
the_post();
$content_types = get_the_terms( $post_id, $taxonomy_categories );
$tag_link = get_field('tag_link');
$tag_host = parse_url($tag_link);
$tag_page = $tag_host['scheme'] . '://' . $tag_host['host'];
?>
{
title : '<?php the_title();?>',
start : '<?php the_field('date');?>'
//only need one item in the array, because with the while loop, this will repeat until all the posts are added.
},
<?php
endwhile;
endif;
?>
]
})
});