I have the following script in the blade.php:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var SITEURL = "{{url('/dash')}}";
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'bootstrap', 'interaction', 'dayGrid', 'timeGrid'],
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,'
},
themeSystem: 'bootstrap',
editable: true,
navLinks: true,
events: SITEURL + "/calendar",
displayEventTime: true,
defaultView: 'timeGridWeek',
selectable: true,
selectHelper: true,
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
And in the controller this part which is get the events from the database:
public function index(Request $request)
{
if(request()->ajax()) {
$returnedColumns = ['id', 'title', 'start', 'end'];
$start = (!empty($request->start)) ? ($request->start) : ('');
$end = (!empty($request->end)) ? ($request->end) : ('');
$events = Event::whereBetween('start', [$start, $end])->get($returnedColumns);
return response()->json($events);
}
return view('/dash/calendar');
}
The Json looks like this, if I remove the if(request()->ajax()) { part:
[{"id":347,"title":"Unavailable","start":"2020-02-11 06:00:00","end":"2020-02-11 06:30:00"}]
Seems the request working fine, but I got JSON parse error, and the calendar just won't show the events. What could be a problem?
Related
I am using FullCalendar in laravel 8 project and I use it to display all the events from the database.
This is the code:
My controller
public function index(Request $request, $id) {
$patient = [];
$listOfPatients = [];
$appointments = [];
//apply permission constraits
$patient = Patient::find($id);
$listOfPatients = Patient::all();
$appointments = appointments::all();
$this->authorize('view', $patient);
// $appointments = $patient->remarks()->get()->sortBy([['id', 'desc']]);
if($request->ajax()) {
$data = appointments::whereDate('start', '>=', $request->start)
->whereDate('end', '<=', $request->end)
->get(['id', 'title', 'description', 'start', 'end']);
return response()->json($data);
}
return view('patient.appointments', [ "appointments" => $appointments, "patient" => $patient, "listOfPatients" => $listOfPatients]);
}
My js
$(document).ready(function () {
var SITEURL = "{{ url('/') }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full_calendar_events').fullCalendar({
editable: false,
editable: false,
eventSources: [
{
url: '/{id}/appointments',
color: '#65a9d7', // an option!
textColor: '#3c3d3d' // an option!
}
],
});
});
I also got this error:
jquery.min.js:4 GET http://127.0.0.1:8000/%7Bid%7D/appointments?start=2022-02-27&end=2022-04-10&_=1648373948124 404 (Not Found)
Route
Route::get('getEvents', [App\Http\Controllers\CalenderController::class, 'index'])->name('event.getEvents');
Controller
public function index(Request $request)
{
$getEvents = Appointment::select('patient_id', 'start_time', 'end_time')->get();
$events = [];
foreach ($getEvents as $values) {
$start_time_format = $values->start_time;
$end_time_format = $values->end_time;
$event = [];
$event['title'] = $values->patient_id;
$event['start'] = $start_time_format;
$event['end'] = $end_time_format;
$events[] = $event;
Debugbar::info($events);
}
return $events;
}
Full Calendar Script
var calendar = new FullCalendar.Calendar(calendarEl, {
editable: true,
droppable: true,
selectable: true,
initialView: getInitialView(),
themeSystem: 'bootstrap',
// responsive
windowResize: function(view) {
var newView = getInitialView();
calendar.changeView(newView);
},
eventDidMount: function(info) {
if (info.event.extendedProps.status === 'done') {
// Change background color of row
info.el.style.backgroundColor = 'red';
// Change color of dot marker
var dotEl = info.el.getElementsByClassName('fc-event-dot')[0];
if (dotEl) {
dotEl.style.backgroundColor = 'white';
}
}
},
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
},
eventClick: function(info) {
addEvent.modal('show');
formEvent[0].reset();
selectedEvent = info.event;
$("#event-title").val(selectedEvent.title);
$('#event-category').val(selectedEvent.classNames[0]);
newEventData = null;
modalTitle.text('Edit Event');
newEventData = null;
},
dateClick: function(info) {
addNewEvent(info);
},
editable: true,
events: 'getEvents',
displayEventTime: true,
eventRender: function(event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
calendar.render();
I have specified the route correctly in this script as events: 'getEvents', you can see that at the end part of the above script.
Now the result in the frontend is:
There is no data displayed from the DB.
And I am getting a console error as: Failed to load resource: the server responded with a status of 404 (Not Found): http://127.0.0.1:8000/getEvents?start=2021-09-26T00%3A00%3A00%2B05%3A30&end=2021-11-07T00%3A00%3A00%2B05%3A30
As you can see there are some unwanted characters in the URL obtained.
The debugging is not working here, I do not know why.. when I add dd($data) or something other there is no debugger part in Frontend.
Please help me to solve this thing.
Thank you.
It is worked. All I was done is correct. The issue was with my route, Due to one function to redirect invalid routes to the 404 page, My route to the controller was not working..
When I put the 404 route to the bottom of all other routes, It is worked.
How to define select2 default AJAX value?
I've tried many but still cannot get it working.
Below is my code:
$("#qrcode_group_rowid").select2({
ajax: {
url: "app/qrcode/qrcode_group_select_service.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 50) < data.total_count
}
};
},
cache: true
},
placeholder: 'Please select',
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 0,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (json) {
if (json.loading) {
return json.text;
}
var markup = json.group_name;
return markup;
}
function formatRepoSelection (json) {
return json.group_name;
}
and my JSON data:
{
"total_count": 897,
"items": [{"id": 901,"group_name": "TEST25-117"},{"id": 1,"group_name": "TEM117"}]
}
What am I doing wrong and how can I fix it?
You should send the following information in the PHP method (there may be a limitation of working with the IP address in eloquent)
/** #var Collection $btsNodes */
$btsNodes = BtsNode::where('node_code' , 'like' , '%'.$request->get('q').'%')
->get(['node_code']);
// ->toArray();
$items = $btsNodes->map(function ($item){
return [
'id' => $item['node_code'],
'node_code' => $item['node_code']
];
});
return ['items' => $items];
I have received as a assignment create 2 applications, one optimized and one unoptimized and i am using free jqGrid to display the data from DB.
I have successfully created both but i would like to track the speed at witch the local operations are done(paging,search,sorting).
I have tried to set up events for each button that triggers the operations, but they dont seem to trigger... i was wondering if there is something better that is built into jqGrid that i could use or a advice that would help me resolve this.
My jqGrid code goes like this:
$(function () {
var colModelSettings = [
{name:'id', label:'id',key: true, hidden: true, width:10,sorttype:'number',editable: true},
{name:'judet',label:'Judet',width:70, align: 'center',editable:true},
{name:'localitate',label:'Localitate',width:80,editable:true,searchoptions: {sopt: ['eq','bw','ew','cn']},align: 'center'},
{name:'tipStrada',label:'tipStrada',editable:true,searchoptions: {sopt: ['eq','bw','ew','cn']},width:100,align: 'center' },
{name:'denumire',label:'denumire',editable:true,width:100,searchoptions: {sopt: ['eq','bw','ew','cn']},align: 'center'},
{name:'cod',label:'cod',width:90,editable:true,align: 'center'}
];
var beforeEvent = 0;
$("#gridAdrese").jqGrid({
pager: $("#pagerGrid"),
url: "/UnoptimizedProject/rest/fetchData",
datatype: "json",
mtype: "POST",
loadonce: true,
forceClientSorting:true,
height: window.innerHeight-250,
sortname: 'id',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
return JSON.stringify(postData);
},
rowNum: 5000,
viewrecords: true,
loadComplete: function(){
if(beforeEvent !== undefined){
var afterEvent = new Date().getTime();
console.log(afterEvent- beforeEvent);
beforeEvent = 0;
}
},
sortorder: 'asc',
caption:'Coduri Postale Neoptimizat' ,
autowidth: true,
colModel: colModelSettings,
});
$("#gridAdrese").jqGrid('navGrid', "#pagerGrid", {edit:false, add:false, del:false, save:false, cancel:false, search:true, searchtext: 'Search', refresh: false});
$("#jqgh_gridAdrese_judet, #jqgh_gridAdrese_localitate, #jqgh_gridAdrese_tipStrada, #jqgh_gridAdrese_denumire, #jqgh_gridAdrese_cod ").on("click",function(){
beforeEvent = new Date().getTime();
console.log("Sorting");
})
$("#fbox_gridAdrese_search").on("click",function(){
beforeEvent = new Date().getTime();
console.log("searching");
});
$("#next_pagerGrid , #last_pagerGrid, #prev_pagerGrid, #first_pagerGrid").on("click",function(){
beforeEvent = new Date().getTime();
console.log("paging");
})
});
You can do about the following:
var startTime, measureTime = false, timeInterval,
startMesure = function () {
startTime = new Date();
measureTime = true;
};
startMesure();
$("#gridAdrese").jqGrid({
url: "/UnoptimizedProject/rest/fetchData",
...
onSortCol: function () {
startMesure();
},
onPaging: function (pgButton, options) {
//if (pgButton === "records") {
startMesure();
//}
},
searching: {
closeAfterSearch: true,
closeAfterReset: true,
closeOnEscape: true,
searchOnEnter: true,
beforeSearch: function () {
startMesure();
return false; // allow filtering
},
onSearch: function () {
startMesure();
},
onReset: function () {
startMesure();
},
},
loadComplete: function () {
if (measureTime) {
timeInterval = new Date() - startTime;
setTimeout(function () {
alert("Total loading time: " + timeInterval + "ms\nFull time: " +
(new Date() - startTime));
}, 50);
measureTime = false;
}
}
}).jqGrid("filterToolbar").jqGrid("navGrid");
We reset startTime with respect of startTime = new Date(); to the current time at the beginning of sorting, paging or filtering.
this my function in controller
public function loadcalendarAction() {
$eventsloaded = $this->container->get('calendarbundle.serviceloadcalendar')->loadCalendar();
$response = new JsonResponse();
//dump($eventsloaded);
//die();
$response->setData(array('events' => $eventsloaded));
return $response;
}
the $eventsloaded is an array of 2 events in my database its OK .. but $response is empty i don't know why ..
and this my calendar_setting.js
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-01-12',
lang: 'ar-tn',
buttonIcons: false, // show the prev/next text
weekNumbers: true,
editable: true,
eventLimit: true, // allow "more" link when too many events
dayClick: function () {
alert('a day has been clicked!');
},
events: Routing.generate('loadcalendar')
});
});
if the response not empty all the events will be displayed in the events:
Look at this questions' answer. You need either to use some external bundle (such as JMSSerializerBundle) to serialize entity, to pass it to json response, or implement something like toArray() method in your entity which will return an array of needed data from entity, after that you could do smth like:
$responseData = [];
foreach ($eventsloaded as $i => $event) {
$responseData[$i] = $event->toArray();
}
return new JsonResponse($responseData);