fullCalendar only adds one event to my calendar - javascript

I have a site that imports a .ics file, saves the information to a table and I am looking to display the events on my fullCalendar.
Here is the code that produces the $events json Object
<?php
$sqlquery2 = db_query("select * from events");
while($eventRow = mysqli_fetch_array($sqlquery2)) {
//$events[] = array(); //Adds the 1st event only
$events = []; //Adds the last event only
array_push($events, json_encode([
'title' => $eventRow['League'],
'start' => $eventRow['StartDate']
]));
foreach($events as $events => $value){
print $value;
}
}
?>
I am able to get this to print a response for each of the (3) rows in my table:
{"title":"GLVC Noncon (D2) Baseball","start":"2023-02-24"}{"title":"GLVC Noncon (D2) Baseball","start":"2023-02-25"}{"title":"MVC Con (D1) Baseball","start":"2023-03-31"}
The problem I have is when adding events to the calendar in my javascript...It adds only the 1st event if I declare $events[] = array(); but only adds the LAST event if I declare $events = [];
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
var eventsJS = new Array();
var eventsJS = <?php print $value;?>;
console.log(eventsJS);
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth timeGridWeek listWeek'
},
initialView: 'dayGridMonth',
events: [eventsJS]
});
calendar.render();
});
</script>
It appears that my variable $events is getting overwritten, but I cannot figure out why or how to stop it from happening!
I have tried using forEach and various looping functions, but I think I have what I need, just need to know why my variable is getting overwritten.
Calendar with 1 event, but 3 objects returned

Related

How to order dates in Google Table Chart using PHP?

I'm creating a table using Google Table Charts and PHP.
The table code is:
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
var data = google.visualization.arrayToDataTable([
<?php echo $dados; ?>
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
data.sort({column: 0, desc: true});
table.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
}
The PHP code (that gets the data) is:
$dados = "['Data','InfoX','InfoY'],";
for($i = 0; $i < count($vet); $i++){
$original_Date = $vet[$i][0];
$New_Date = date("d/m/Y", strtotime($original_Date));
$dados .= "['".$New_Date."',".$vet[$i][2].",".$vet[$i][3].','."]";
if ($i+1 < count($vet)){
$dados .= ",";
}
Currently, the table looks like this:
As you can see, I have a problem with the way the first column is sorted (right now, it is ordering first by the day, then the month and the year).
I need to order the first column chronologically (year-month-day), but show it in a dd/mm/yyyy format (in HTML, it is like when you use data-search and data-order). Is there any option custom propriety or option that I need to use to solve my issue?
Thanks in advance for the answers and feel free to ask for more details if you need it.
the problem is the dates are coming across as strings.
with real dates, the sort function will work correctly.
try using the following php...
$New_Date = date("m/d/Y", strtotime($original_Date));
$dados .= "[new Date('".$New_Date."'),".$vet[$i][2].",".$vet[$i][3].','."]";
then in javascript, use a date formatter to format the date column...
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
var data = google.visualization.arrayToDataTable([
<?php echo $dados; ?>
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
data.sort({column: 0, desc: true});
var formatDate = new google.visualization.DateFormat({pattern: 'dd/MM/yyyy'});
formatDate.format(data, 0);
table.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
}

Jquery Full Calendar plugin not rendering first tab

I have a couple of FullCalendar instances each in its own Tab.
At first when I switched tabs, the calendars did not display, so I added this part to render the calendars once you click on a tab
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var redrawcal = $(this).attr('href');
redrawcal = redrawcal.substring(1,redrawcal.length);
$('#calendar_'+redrawcal).fullCalendar('render');
$('.fc-today').removeClass('fc-today');
});
This works perfectly for each tab after the first, however, the first Tab's calendar's event times are incorrect.
As shown in the image below, the second tab's events are correct:
But The first tab does not rerender the events correct, the initial placement and the placement if you switch tabs are exactly the same, as seen in the image below:
I have the following code that's suppose to render the calendar after it has been created at first:
$(function(){
//first tab's calander is not rendering correctly, this will make it show correct from the start
<?php $branch = $branches[0]; ?>
<?php $branch_studio_id = str_replace(" ", "_", $branch['branch_studio_name']); ?>
<?php $branch_studio_id = preg_replace("/[^a-zA-Z]/", "", $branch_studio_id); ?>
$('#calendar_<?= $branch_studio_id; ?>').fullCalendar('render');
});
For this example, the calendar's id is calendar_Centurion, the PHP simply removes spaces and special characters
I have also tried this:
$('#calendar_<?= $branch_studio_id; ?>').fullCalendar('rerenderEvents');
But I still have the same results.
The two events in the two calendars have exactly the same times on the same day, and all information is the same
If there is only one Tab, it is broken without an extra tab to rerender the calendar.
I have basically tries everything that I could find and that I could think of that might help but with no positive results.
Unfortunately I cannot create a fiddle of this as it would take quite long to do so and the actual code/project is not open to the public as of yet.
I do hope this can be easily solved.
Thanx in advance!
UPDATE
Below is the HTML and JS code for my calendars
<?php $branch_studio_id = str_replace(" ", "_", trim($branch['branch_studio_name'])); ?>
<?php $branch_studio_id = preg_replace("/[^a-zA-Z]/", "", $branch_studio_id); ?>
<div class="tab-pane <?=($x == 1) ? 'active' : '' ?>" id="<?=$branch_studio_id ?>">
<div class="row">
<div class="col-md-9">
<div id="calendar_<?= $branch_studio_id ?>"></div>
</div>
<div class="col-md-3">
<p class="h4 text-light">Classes not on timetable</p>
<hr />
<div id='external-events_<?=$branch_studio_id ?>'>
<?php foreach ($classes_notimetable as $class) :?>
<?php if ($class['studio_id'] == $branch['studio_id']) : ?>
<div class="external-event label label-success" data-event-class="fc-event-success" data-class-id="<?=$class['id']?>"><?=$class['class_name'] ?></div>
<?php endif;?>
<?php endforeach;?>
<hr />
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function($) {
'use strict';
var initCalendarDragNDrop<?=$x;?> = function() {
$('#external-events_<?=$branch_studio_id ?> div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject<?=$x;?> = {
title : $.trim($(this).text()), // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject<?=$x;?>);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex : 999,
revert : true,
revertDuration:0
});
});
};
var initCalendar<?=$x;?> = function() {
var $calendar<?=$x;?> = $('#calendar_<?=$branch_studio_id ?>');
var date = new Date();
var daynum = date.getDay();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$calendar<?=$x;?>.fullCalendar({
header: {left: '', center: '', right: ''},
defaultView: 'agendaWeek',
timeFormat: 'HH:mm',
slotDuration: '00:10:00',
snapDuration: '00:05:00',
firstDay : 1,
columnFormat: 'ddd',
minTime:'<?= (isset($school_custom['school_from_hour'])) ? $school_custom['school_from_hour'] : '08'; ?>:<?= (isset($school_custom['school_from_minutes'])) ? $school_custom['school_from_minutes'] : '00'; ?>',
maxTime: '<?= (isset($school_custom['school_to_hour'])) ? $school_custom['school_to_hour'] : '21'; ?>:<?= (isset($school_custom['school_to_minutes'])) ? $school_custom['school_to_minutes'] : '00'; ?>',
allDaySlot: false,
defaultTimedEventDuration: '01:00:00',
forceEventDuration:true,
editable : true,
eventDrop: function(event) {
var eventid = event.id;
var eventday = (event.start._d).getDay();
var eventstarthour = (event.start._d).getHours()-2;
var eventstartminute = (event.start._d).getMinutes();
var eventendhour = (event.end._d).getHours()-2;
var eventendminute = (event.end._d).getMinutes();
$('').postJsonCheck('classes/update_class_times', {event_id: eventid, event_day:eventday, event_starthour:eventstarthour,event_startminute:eventstartminute,event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
},
droppable : true, // this allows things to be dropped onto the calendar !!!
drop : function(date) {// this function is called when something is dropped
var $externalEvent = $(this);
// retrieve the dropped element's stored Event Object
var originalEventObject = $externalEvent.data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
//copiedEventObject.allDay = allDay;
copiedEventObject.className = $externalEvent.attr('data-event-class');
var classid = parseInt($(this).attr('data-class-id'));
copiedEventObject.id = classid;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar_<?=$branch_studio_id ?>').fullCalendar('renderEvent', copiedEventObject, true);
//Update DB
var eventday = (copiedEventObject.start._d).getDay();
var eventstarthour = (copiedEventObject.start._d).getHours()-2;
var eventstartminute = (copiedEventObject.start._d).getMinutes();
var eventendhour = (copiedEventObject.start._d).getHours()-1;
var eventendminute = (copiedEventObject.start._d).getMinutes();
$('').postJsonCheck('classes/add_class_timetable', {class_id: classid, event_day:eventday, event_starthour:eventstarthour,event_startminute:eventstartminute,event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
//remove the event from the not on timbetable list
$(this).remove();
},
eventResize: function(event, delta, revertFunc) {
var classid = event.id;
var eventendhour = (event.end._d).getHours()-2;
var eventendminute = (event.end._d).getMinutes();
$('').postJsonCheck('classes/update_class_duration', {class_id: classid, event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
},
events : [<?php $z = 0;?>
<?php foreach ($classes as $class): ?>
<?php $z++;?>
<?php if ($class['studio_id'] == $branch['studio_id']) : ?>
{
id: <?=$class["day_id"]?>,
title: '<?=$class["class_name"]?>',
start: new Date(y, m, d-(daynum-<?=$class["day"]?>), '<?=$class["start_hour"]?>', '<?=$class["start_minute"]?>'),
end: new Date(y, m, d-(daynum-<?=$class["day"]?>), '<?=$class["end_hour"]?>', '<?=$class["end_minute"]?>')
}
<?php if ($z < count($classes))echo ","?>
<?php endif;?>
<?php endforeach; ?>]
});
};
$(function() {
initCalendar<?=$x;?>();
initCalendarDragNDrop<?=$x;?>();
});
}).apply($(this), [jQuery]);
</script>
*Please note that there is a php foreach loop outside of the above code, so this code gets duplicated for each calendar, each with a unique $branch_studio_id used in the calendar's ID

Updating Pickadate Input via AJAX

I use Pickadate.js and JQuery Form Plugin. I have date and time pickers seperately. What I want to do is to disable times in timepicker according to value of datepicker. So, I am trying to get the JSON data into picker.set("disable", [ ]);. I can console.log the plain text but it remains aimless.
I tried a lot and have come across these solutions in that question. But I couldn't launch them. (I adapted pickadate functions and classes to pickatime's.)
// Javascript
$(document).ready(function() {
$("input").click(function() {
$(".datepicker").pickadate({
format: 'yyyy-mm-dd',
formatSubmit: 'yyyy-mm-dd',
min: true,
max: false
});
var $input = $(".timepicker").pickatime({
format: 'HH:i',
formatSubmit: 'HH:i',
formatLabel: 'HH:i'
});
$('.datepicker').change(function() {
$('#form').ajaxSubmit({
target: '#check_result',
url: 'check.php',
success: function showResponse(responseText, $form) {
var picker = $input.pickatime('picker');
picker.set("disable", [
console.log(responseText)
]);
}
});
return false;
});
});
});
// PHP (check.php)
<?php
// Database connection done.
$date = mysqli_real_escape_string($con, $_POST['date']);
$match_query = mysqli_query($con, "SELECT * FROM booking WHERE DATE(time) = '$date'");
$disabled_times = array();
if ($result = $match_query) {
while ($row = mysqli_fetch_assoc($result)) {
$disabled_times[] = $row['time'];
}
mysqli_free_result($result);
}
echo implode($disabled_times);
?>
Can you post an example of the json being returned from your php?
According to the docs (http://amsul.ca/pickadate.js/api/#method-get-disable)
your json should be something like this: [2,30], [4,30], [9,0]
If your json is correct, be sure it is not being passed to the timepicker as a string. Try something like:
var json = JSON.parse(responseText);
picker.set("disable", [ json ]);
UPDATE:
I guess with the following code, your json will return properly:
...
$time = explode(',', $row['time']);
$time[0] = (int)$time[0];
$time[1] = (int)$time[1];
$disabled_times[] = $time;
...
echo json_encode($disabled_times);

Populate PHP data in JQuery FullCalendar

I have a JQuery calendar plugin I'm using currently and as of right now I'm stuck on trying to figure out how to populate the calendar with information from a PHP file using AJAX.
var Script = function () {
// calendar
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
/*---------------------------------------------------------------------------*/
window.onload = function myfunction() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("calendar").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../ajax/calendar.php", true);
xmlhttp.send();
}
/*---------------------------------------------------------------------------*/
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: false,
events: [
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
]
});
}();
This is the PHP File
<?
$query = mysql_query("SELECT * FROM table WHERE id = '1093'");
do {
$message = $row['message'];
$hour = $row['hour'];
$minute = $row['minute'];
$year = $row['year'];
$month = $row['month'];
$day = $row['day'];
$status = $row['status'];
if(eregi('pending', $status)) {
echo '
{<br>
title: '.$message.',<br>
start: new Date('.$year.', '.$month.', '.$day.', 12, 0),<br>
end: new Date('.$year.', '.$month.', '.$day.', 14, 0),<br>
allDay: false<br>
},
';
}
}while($row = mysql_fetch_array($query));
} else header('location: error.php');
?>
How do I get the info from my database table to loop into my JQuery plugin?
PHP have a json_encode() method allowing you to convert PHP arrays to valid JSON objects.
Also make sure to output the correct content-type header.
header('Content-Type: application/json');
echo json_encode($my_datas_from_DB);
Just output your content with this method so it can be consumed by JavaScript.
(Side note: JSON is not HTML, <br> wouldn't be valid here as you try to output JSON manually)
It's much easier than you think, you can define your events property as an ajax call like so (right in your fullcalendar initialization):
...
events: {
url: '../phpPath/pathToEventScript.php',
dataType: 'json',
type: "POST"
},
...
just be sure that each event object (in your array of objects) has a start property.
PHP script:
$select = "SELECT title, start FROM events";
$stmt = $db->query($select);
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($events);
Do something like this:
"your.js" could be something like this:
$.get( "../ajax/calendar.php", function( data ) {
$('#calendar').fullCalendar(eval("(" + data + ")"))
alert( "Calendar initilazed ;)" );
});
and your php file havenot to include "< br >" tag as new line!

Google map custom marker based on database

In 2 weeks I explored much about Google maps. I am try read a forum and tutorial. But I got this problem when I am going to develop a GIS web. I am using Google maps apiv3, postgre database, and php. I have so much row in my database. Now I only can show multiple marker based on my database, but what I after is the marker have a unique icon based on column content in database like a type 1 = 1.png type 2 = 2.png. the problem is the type is too many, so it is impossible to definition them by manual (because so many type, I already have about 30 type of content in database column ) . I get database value using json. I've already try read forum and some tutorial, but I can't find the answer. sorry for my bad english. please help me, thanks.
this is the code index.php and json.php :
<html lang="en">
<head>
<script type="text/javascript">
function initialize(){
var peta;
var gambar_tanda;
gambar_tanda = 'assets/images/enseval.jpg';
var x = new Array();
var y = new Array();
var customer_name = new Array();
var rayon_name = new Array();
// posisi default peta saat diload
var lokasibaru = new google.maps.LatLng( -1.2653859,116.83119999999997);
var petaoption = {
zoom: 5,
center: lokasibaru,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function ambilpeta() untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
//rayon_name[i] = msg.enseval.customer[i].nama_rayon
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, msg.enseval.customer[i].nama_customer );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
</script>
<?php
require ('config.php');
$rayon = $_POST['rayon'];
$cabang = $_POST['org_id'];
//echo "$rayon, $cabang, $rayonhasil";
$sql = "SELECT distinct org_id, customer_name, attribute16, attribute17 FROM hasilgis";
$data = pg_query($sql);
$json = '{"enseval": {';
$json .= '"customer":[ ';
while($x = pg_fetch_array($data)){
$json .= '{';
$json .= '"id_customer":"'.$x['org_id'].'",
"nama_customer":"'.htmlspecialchars($x['customer_name']).'",
"x":"'.$x['attribute17'].'",
"y":"'.$x['attribute16'].'"
},';
}
$json = substr($json,0,strlen($json)-1);
$json .= ']';
$json .= '}}';
echo $json;
?>
I'm not sure what's the problem :)
The only thing you must do is to generate icons for all types. You don't have to do it manually - just create a scipt that will generate icons of different colors for every type and name it like 1.jpg, 2.jpg, ...
Pass type via your json message and than on client side create icon url dynamically:
gambar_tanda = 'assets/images/'+msg.enseval.customer[i].type+'.jpg';

Categories

Resources