FullCalendar get events from database - javascript

Hi i am using FullCalendar in a laravel project and i need to display the events from the database.
I get all the events from the database and display them using json_encode.
There is the code i use :
My controller :
<?php
namespace App\Http\Controllers;
use App\Http\Gestionnaires\EventGestionnaire;
use Illuminate\Http\Request;
class EventController extends Controller
{
public function afficher(){
$eventGestionnaire = new EventGestionnaire;
$listeEvents = $eventGestionnaire->getListeEvents();
echo json_encode($listeEvents);
return view('pages.calendar');
}
}
And my script :
$calendar.fullCalendar({
viewRender: function(view, element) {
if (view.name != 'month'){
$(element).find('.fc-scroller').perfectScrollbar();
}
},
resourceEditable: true,
eventLimit: true,
editable: true,
selectable: true,
selectHelper: true,
header: {
left: 'month,agendaWeek,agendaDay',
center: 'title',
right: 'prev,next,today'
},
events: 'EventController.php',
The error :
jquery.min.js:3049 GET http://localhost/planner/public/EventController.php?start=2019-09-01&end=2019-10-13&_=1568831263931 404 (Not Found)

I used it in the past, and using the same structure for the javascript side of it as previous answer shows. Once created your route to access it, see php code for responding to your ajax request:
$results = [];
foreach($calendar_events as $calendar_event)
{
$ev = [];
$ev["title"] = $calendar_event->name;
$ev["color"] = $calendar_event->calendar->color ?? "f47d30";
$ev["start"] = Carbon::parse($calendar_event->start)->format("Y-m-d");
$ev["end"] = Carbon::parse($calendar_event->end)->format("Y-m-d");
if (!$calendar_event->is_allday)
{
$ev["start"] = Carbon::parse($calendar_event->start."T".$calendar_event->start_time)->format("Y-m-d\TH:i:s");
$ev["end"] = Carbon::parse($calendar_event->end."T".$calendar_event->end_time)->format("Y-m-d\TH:i:s");
$ev["allDay"] = false;
}
if (!empty($calendar_event->url))
{
$ev["url"] = $calendar_event->url;
}
$results[] = $ev;
}
return response($results);

From FullCallendar V3 DOCS to pass URL with JSON response use
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: '/myfeed.php', // use the `url` property
color: 'yellow', // an option!
textColor: 'black' // an option!
}
// any other sources...
]
});

Related

Fetching API data in Angular for fullcalendar

I have the function to return the api data for the user bills, and then mapped the data to conform to fullcalendar - when I console log the "this.calendarBills" its json format and the date is also formatted correctly, but when I set "events" for fullcalendar to this.calendarBills, it returns nothing on the calendar...
export class BillPageComponent implements OnInit {
userId = localStorage.getItem('userId') || '';
token = localStorage.getItem('token') || '';
bills: Bill[] = [];
calendarBills: [] = [];
calendarOptions: CalendarOptions | undefined;
constructor(
public fetchApiData: FetchApiDataService,
public snackBar: MatSnackBar,
public dialog: MatDialog,
) { }
ngOnInit(): void {
this.getBills(this.userId, this.token);
}
getBills(userId: string, token: string): void {
this.fetchApiData.getBills(userId, token).subscribe((resp: any) => {
this.bills = resp;
this.calendarBills = resp.map((e: any) => ({ title: e.Description, date: e.Date }))
console.log(this.bills);
console.log(this.calendarBills);
this.calendarOptions = {
headerToolbar: {
center: 'title',
},
initialView: 'dayGridMonth',
eventSources: this.calendarBills,
events: this.calendarBills, // alternatively, use the `events` setting to fetch from a feed
weekends: true,
editable: true,
selectable: true,
selectMirror: true,
dayMaxEvents: true,
dateClick: this.handleDateClick.bind(this),
// select: this.handleDateSelect.bind(this),
// eventClick: this.handleEventClick.bind(this),
// eventsSet: this.handleEvents.bind(this)
/* you can update a remote database when these fire:
eventAdd:
eventChange:
eventRemove:
*/
};
})
}
handleDateClick(arg: { dateStr: string; }) {
alert('date click! ' + arg.dateStr)
}
thanks for the help! Managed to find the problem - had to call the calendarOptions INSIDE the getBills. Also, big thanks to ADyson (those are the types of issues I have without realizing!)
getBills(userId: string, token: string): void {
this.fetchApiData.getBills(userId, token).subscribe((resp: any) => {
this.bills = resp;
this.calendarBills = resp.map((e: any) => ({ title: e.Description, start: e.Date, allDay: true }));
console.log(this.bills);
console.log(this.calendarBills);
// return this.calendarBills;
this.calendarOptions = {
headerToolbar: {
center: 'title',
},
initialView: 'dayGridMonth',
events: this.calendarBills, // alternatively, use the `events` setting to fetch from a feed
weekends: true,
editable: true,
selectable: true,
selectMirror: true,
dayMaxEvents: true,
dateClick: this.handleDateClick.bind(this),
// select: this.handleDateSelect.bind(this),
// eventClick: this.handleEventClick.bind(this),
// eventsSet: this.handleEvents.bind(this)
/* you can update a remote database when these fire:
eventAdd:
eventChange:
eventRemove:
*/
};
})
}
You said
the date is also formatted correctly
...maybe so, but fullCalendar doesn't recognise or understand date as a property name of an event. It will not read it and use it as a date. Therefore, fullCalendar doesn't know where to place your event on the calendar, which is why you can't see it.
The names of the fields you can use in your events are clearly documented already at https://fullcalendar.io/docs/event-parsing. You need to specify start (for the start date/time of the event) and optionally also end (for the end date/time).
Assuming your date really is formatted correctly (as per https://fullcalendar.io/docs/date-parsing) then
{ title: e.Description, start: e.Date }
should work for you.

how to solve Trying to get property 'bids' of non-object error

I want to display data from bid table in a form of datatable. But I get this error
"Trying to get property 'bids' of non-object" if it doesn't have bids.The bids model is connected to auction model and the auction model is connected to media site model. How to make it display blank record if it doesn't have data.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Auction;
use App\Bid;
use App\User;
use App\Media;
use App\MediaSite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MediaSiteController extends Controller
{
public function show(MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
$bids = $auction->bids;
return view('admin.media-site.show', ['mediaSite' => $mediaSite,'auction' => $auction], compact('auction'));
}
My view:
<body>
<div id="datatable-bid"></div>
</body>
<script>
$(document).ready(function () {
var datatableBid = $('#datatable-bid').mDatatable({
// datasource definition
data: {
type: 'local',
source: {!! json_encode($auction->bids) !!},
pageSize: 10
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false,
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
search: {
input: $('#panel-search')
},
// columns definition
columns: [
{
field: "price",
title: "Price",
}, {
field: "month",
title: "Month",
},{
field: "user_id",
title: "User Id",
}
]
});
</script>
Here is my error:
Trying to get property 'bids' of non-object
place following after $auction = $mediaSite->auction;
if($auction){
$bids = $auction->bids;
}else{
//put following line or whatever you need to do if there is no data comes
$auction = [];
}
In the show() function make these changes
$auction = $mediaSite->auction;
if($auction) {
$bids = $auction->bids;
} else {
$bids = [];
}
// now send $bids to view along with $auction
// may be like this
// return view(..., compact($auction, $bids));
Then, in your view make this change
// datasource definition
data: {
type: 'local',
source: {!! json_encode($bids) !!},
pageSize: 10
},
See if this helps.

How can i read events from my database table and show them in their respective dates in java script and jquery

i use Full calendar plugin to do this and i have done something but still did not get up to mark.
hear is my scripting code
$('#calendar').fullCalendar({
//theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {//This is to add icons to the visible buttons
prev: "<span class='fa fa-caret-left'></span>",
next: "<span class='fa fa-caret-right'></span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar
drop: function(date) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).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.backgroundColor = $(this).css("background-color");
copiedEventObject.borderColor = $(this).css("border-color");
console.log(copiedEventObject);
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
/*alert(date + ' was moved ' + allDay + ' days\n' +
'(should probably update your database)');*/
},
//events:"web_master/mycal/ajax_fetch_calendar_data",
events: function(start, end, timezone, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
//console.log(doc);
var events = [];
$(doc).find('event').each(function(){
console.log(doc);
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
}
});
},
});
in this i successfully found my doc in events section.
here is the code to fetch events from DB
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
#pr($info);
for($i = 0 ; $i < count($info) ; $i++)
{
$rows[]= array("id"=>$info[$i]['i_id'],
"title"=> $info[$i]['s_title'],
"start"=> $info[$i]['dt_start_date'],
"end"=>$info[$i]['dt_end_date'],
"allDay"=> $info[$i]['s_allDay']);
}
if($rows)
{
echo json_encode($rows);
}
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}
but there is an find(event) function which is didn't found.
Basically what i need to do that
i have some events, those are fetch from DB and i have to drag them on the specific date on the date that comes(upto this done), but i want to store that in Db and fetch them from DB.
I am new to java script and jquery and i didn't know about JSON also.
any help regarding this will helpfull to me.
Thanks.
Well
After few days I have done it myself.
And I think it would be help full to someone So i update my Question
In the Events Section of Fullcalendar for reading multiple events and showing them in your Fullcalendar
events: function(start, end, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
var eventObject = [];
for(i=0;i<doc.length;i++)
{
eventObject.push({
id : doc[i].id,
start : doc[i].start,
end : doc[i].end,
title : doc[i].title
//allDay : doc[i].allDay,
//backgroundColor : doc[i].backgroundColor,
//borderColor : doc[i].borderColor
});
}
callback(eventObject);
}
});
},
And i fetch it from my DB in this way
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
echo json_encode($info);
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}

Fullcalendar - Can we add custom data to our event Json Data?

I want to send a type in my Event Json Response.
Here is my code:
$('#calendar').fullCalendar({
eventSources: [
{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}
]
});
You see I send a type in JSON Response array, is this possible? What parameter can we use for sending our custom data?
As per the documentation:
Non-standard Fields
In addition to the fields above, you may also include your own non-standard fields in each Event Object. FullCalendar will not modify or delete these fields. For example, developers often include a description field for use in callbacks such as eventRender.
Example:
$('#calendar').fullCalendar({
events: [
{
title: 'My Event',
start: '2010-01-01',
type: 1 // Custom field
}
],
eventRender: function(event, element) {
console.log(event.type); // Writes "1"
}
});
Try It with events: instead of eventSources:
$('#calendar').fullCalendar({
events: [
{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}
]
});
In the new version you should do this:
eventRender: function (info) {
info.el.firstChild.innerHTML = info.event.extendedProps.type + " " + info.event.extendedProps.customEventsClass;
}
In version 4 custom data is in extendedProps.
In short e.event.extendedProps
You can also pass url endpoint to events as long as the url returns json response
cId.fullCalendar({
header: {
right: '',
center: 'prev, title, next',
left: ''
},
theme: true, //Do not remove this as it ruin the design
selectable: true,
selectHelper: true,
editable: true,
//it will load data from this url
events: "{{ url('api/events') }}",
// events: getData(),
//Add Events
});
and in your controller or function
$events = $request->user()->events()->select('title','color','date')->get();
// dd($even,$events)
$eventsResponse = [];
// created_at->format('Y-m-d')
foreach ($events as $event)
{
$eventsResponse[] = [
'title'=>$event->title,
'color'=>$event->color,
'start'=> Carbon::parse($event->date)->toDateTimeString(),
];
}
return $eventsResponse;

Jquery fullcalendar not showing events

I was very excited to see a calendar plugin like fullcalendar. I am trying to use fullcalendar to display events for each month. But the events are not displayed on the calendar.
My code is :
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult HighlightCalendar()
{
var tasksList = new List<HighlightMonthlyEvents>();
tasksList.Add(new HighlightMonthlyEvents
{
id = 1,
EventName = "Google search",
EventStartDate = ToUnixTimespan(DateTime.Now),
EventEndDate = ToUnixTimespan(DateTime.Now.AddHours(4)),
url = "www.google.com"
});
tasksList.Add(new HighlightMonthlyEvents
{
id = 1,
EventName = "Bing search",
EventStartDate = ToUnixTimespan(DateTime.Now.AddDays(1)),
EventEndDate = ToUnixTimespan(DateTime.Now.AddDays(1).AddHours(4)),
url = "www.bing.com"
});
var highlightDays = Jayrock.Json.Conversion.JsonConvert.ExportToString(tasksList.ToArray());
return Json(highlightDays, JsonRequestBehavior.AllowGet);
}
<script type="text/javascript">
$(function () {
// FullCalendar
$('.fullcalendar').fullCalendar({
theme: true,
header: {
left: 'today prev,next',
center: '',
right: ''
},
defaultView: 'month',
editable: false,
events: function (callback) {
// do some asynchronous ajax
contentType: "application/json; charset=utf-8",
$.getJSON("/Test/HighlightCalendar/", null,
function (result) {
var calevents = new Array();
var results = eval(result);
eval(results.length);
if (results != null) {
for (i in results) {
var calEvent = results[i];
calevents.push(calEvent)
}
}
alert(calevents.length);
// then, pass the CalEvent array to the callback
callback(calevents);
});
}
});
And as for my JSON, it looks like:
[{"id":1,"allDay":false,"title":"Google search","start":1279750267,"end":1279764667,"url":"www.google.com"},{"id":2,"allDay":false,"title":"Bing search","start":1279836667,"end":1279851067,"url":"www.bing.com"}]
What do you think about what is wrong?
This might probably has to do with quotes around your property and values.
Try to include quotes in both property and value and check your result.
I achieved the same without using JSON.js like this.
System.Web.Script.Serialization.JavaScriptSerializer eventListSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string eventListJSON = eventListSerializer.Serialize(addevList);

Categories

Resources