Laravel Livewire: Possible to use AJAX? - javascript

The programming language we've used is: Laravel Livewire.
In the application there's 2 users: 1) Member; 2) Admin.
We have module called "Activities" where the admin can only create,read,update and inactive/active while the Member has a dashboard where they can see all active activities.
I implemented the fullCalendar, I managed to fetch and display the data. Now what I want is when the activity is clicked, it will show the activity details will using modal.
Controller
public function getActivityDetails(Request $request)
{
$data = $request->all();
$activity = Activity::where('id',$data['id']);
dd($activity);
return response()->json($activity);
}
View
<script>
$(document).ready(function(){
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
}
});
var activities = #json($activities);
var calendar = $('#calendar').fullCalendar({
header:{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek, agendaDay'
},
events: activities,
selectable: true,
selectHelper: true,
selectable: true,
eventClick: function(event) {
if (event.id) {
$.ajax({
url: "/members-dashboard/getActivityDetails",
type: "POST",
data: {
id: event.id
},
success:function(data){
console.log(data);
}
})
}
}
// select: function(start, end, allDays){
// var value = $(this).val();
// console.log(value);
// $('#exampleModal').modal('toggle');
// }
});
function successResponse(data)
{
calendar.fullCalendar('refetchEvents');
}
});
</script>
WEB
use App\Http\Livewire\MembersPortal\MembersDashboard\ActivityDetails;
Route::post('/members-dashboard/getActivityDetails',MembersDashboard::class,'getActivityDetails')->middleware((['auth']));
NOTE: When I tried to console.log the data, it gives me all the html
Question: How can I return the value in my controller?

I think that you could use Two components
Activities an ActivitiyDetails components.
The first component will fetch all activities and eager loads activity details at the mount method.
$public Activity $activities;
public function mount(){
$this->activities= Activity::with('details')->where(...);
}
After that in your view you will have all your activities and the related activitities detail avoiding to use JQuery to fetch detail for each activity.
The second component could be ActivityDetail, which will accept a param of type ActivityDetail object.
In your view
<div>
#foreach ($activities as $activity)
<livewire:activity-detail :post="$activity->details">
#endforeach
</div>
I hope this help.

Related

FullCalendar not showing extraParams

I am having some problems retrieving these from my string
here is my script, taken from the website..
events: {
url: '/CalendarManager/Findall',
method: 'GET',
extraParams: {
custom_param1: 'customerName',
custom_param2: 'description'
},
failure: function () {
alert('there was an error while fetching events!');
},
eventRender: function (event, element) {
element.qtip({
content: event.custom_param1,
content: event.custom_param2
});
}
},
UPDATE: 12/24/2020
To answer questions below.. I am using 5.3.2 version. I can use this as well and it will bring back everything but the custom parameters.
events: '/CalendarManager/Findall',
I am using Json pulling from DB - Below is the code..
public ActionResult FindAll()
{
return Json(db.GetEvents.AsEnumerable().Select(e => new
{
id = e.CompanyId,
companyName = e.CompanyName,
title = e.Title,
description = e.Description,
allDay = e.AllDay,
start = e.StartDate.ToString("yyyy-MM-ddTHH:mm:ss"),
end = e.EndDate.ToString("yyyy-MM-ddTHH:mm:ss"),
color = e.Color
}).ToList(), JsonRequestBehavior.AllowGet);
}
I changed the version I was using and that is when the extras did not show up. So I added what I thought the documentation said to use.
Adding the extra Params after the url did not work..
UPDATE:
I read through the suggested. I guess I am still not understanding or maybe not getting "Where I am supposed to put the code".
I believe I need to use eventContent. I also did use the console.log(info.event.extendedProps.companyName); Which is great, it does show up in the console window, However i need it on the calendar not in the console window. FullCalendar's examples could be a little better!
Here is what I did but still does not show on the calendar.
eventDidMount: function (info) {
var tooltip = new Tooltip(info.el, {
title: info.event.extendedProps.description,
placement: 'top',
trigger: 'hover',
container: 'body'
});
console.log(info.event.extendedProps.companyName);
},
eventSources: [{
url: '/CalendarManager/Findall',
failure: function () {
alert('there was an error while fetching events!');
},
}],
eventContent: function (arg) {
html: arg.event.extendedProps.companyName
}
I did add some stuff in there to produce just a bubble when hovered over with this info but it does not work either.
Thank You!
UPDATE: 12/27/2020 Working Code
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prevYear,prev,next,nextYear today',
center: 'title',
right: 'dayGridMonth,dayGridWeek,dayGridDay,listWeek'
},
initialView: 'dayGridMonth',
navLinks: true, // can click day/week names to navigate views
editable: true,
dayMaxEvents: true, // allow "more" link when too many events
themeSystem: 'bootstrap',
selectable: true,
selectMirror: true,
//Random default events
//events: '/CalendarManager/Findall',
eventDidMount: function (info) {
var tooltip = new Tooltip(info.el, {
title: info.event.extendedProps.description,
placement: 'top',
trigger: 'hover',
container: 'body'
});
console.log(info.event.extendedProps.companyName);
},
events: {
url: '/CalendarManager/Findall',
failure: function () {
alert('there was an error while fetching events!');
},
},
eventContent: function (arg) {
return { html: arg.event.title + '<br>' + arg.event.extendedProps.companyName + '<br>' + arg.event.extendedProps.description };
}
});
calendar.render();
Thank you for all your help!
First, let me know what kind of version of fullcalendar you are using.
fullcalendar v5.5 doesn't provide eventRender.
And extraParams is not what you want to show. It is the query params which attach after the request url, like http://example.com/CalendarManager/Findall?custom_param1=customerName&....
If you want to use extend event props then you should parse them as extendProps.
And you should use Event Render Hooks rather than eventRender if you are using the latest version.
How to fix:
Anyway, you should use function, not an object.
You can use events (as a function)
function( fetchInfo, successCallback, failureCallback ) { }
You can also use events (as a json feed)
var calendar = new Calendar(calendarEl, {
events: '/myfeed.php'
});
If you are going to use object rather than function, then you can use eventSources
And if you want to handle the success response, then use eventSourceSuccess function
Here is an example (using fullcalendar v5.5):
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'listWeek',
loading: function(bool) {
if (bool) {
$("#dashboard-calendar-column .pre-loader").show();
} else {
$("#dashboard-calendar-column .pre-loader").hide();
}
},
// get all events from the source
eventSources: [{
url: '/CalendarManager/Findall',
method: 'GET',
failure: function() {
document.getElementById('script-warning').style.display = 'block'
}
}],
// convert the response to the fullcalendar events
eventSourceSuccess: function(content, xhr) {
var events = [];
content.events.value.map(event => {
events.push({
id: event.id,
allDay: event.isAllDay,
title: event.subject,
start:event.start.dateTime,
end: event.end.dateTime,
// The followings are what you want to add as extended
custom_param1: 'customerName',
custom_param2: 'description',
// Or you could add them to the extendedProps object
extendedProps: {
custom_param1: 'customerName',
custom_param2: 'description',
description: event.bodyPreview,
...
},
// You can check fullcalendar event parsing
...
})
})
return events;
},
eventDidMount: function (arg) {
// remove dot between the event titles
$(arg.el).find('.fc-list-event-graphic').remove();
// You can select the extended props like arg.event.custom_param1 or arg.event.extendProps.custom_param1
...
},
});
calendar.render();
})
Hope this would help you.
You can use extraParams using eventSources if you are using fullcalendar v5.
eventSources: [{
url: '/CalendarManager/Findall',
method: 'POST',
extraParams: {
custom_param1: 'customerName',
custom_param2: 'description'
}
...
}]
You should use POST rather use GET, then it will work.

filter fullcalendar events with select(not work)

I need to filter the events that are displayed on the screen using a select. I am using .change to send the value of the selected option and the screen is refreshed, but I have not been successful.The events are displayed correctly if I remove the WHERE. I think the model is not getting the value of rut_usu. Any help is welcome.
Controller ( cCalendar )
public function geteventos(){
$rut_usu = $this->input->post('rut_jc');
$r = $this->mCalendar->geteventos();
echo json_encode($r, $rut_usu);
}
Model (mCalendar)
public function geteventos($rut_usu){
$this->db->select('CONCAT(estudiantes.pnombre," ", estudiantes.apellido_pa," ", estudiantes.apellido_ma,", ",motivos_citas.descripcion_mot) As title ,citas.id_ci id, citas.fecha_ini start, citas.fecha_ter end, citas.id_mot mot, CONCAT(estudiantes.pnombre," ", estudiantes.apellido_pa," ", estudiantes.apellido_ma) as estudiante');
$this->db->select('CONCAT(usuarios.pnombre," ", usuarios.apellido_pa," ", usuarios.apellido_ma) as jefe_c, estudiantes.rut_estu rut_estudiante');
$this->db->from('citas');
$this->db->join('estudiantes', 'citas.rut_estu = estudiantes.rut_estu');
$this->db->join('motivos_citas','citas.id_mot = motivos_citas.id_mot');
$this->db->join('usuarios','citas.rut_usu = usuarios.rut_usu');
$this->db->where('rut_usu',$rut_usu);
return $this->db->get()->result();
}
Javascript (send select value to filter events)
$("#rut_jc").change(function(){;
//rut_jc is the name of the select
var rut_usu = $("#rut_jc").val();
$.ajax({
url: "<?php echo base_url(); ?>" + "cCalendar/geteventos/",
type: 'post',
data: { "rut_jc": rut_usu },
success: function(response){
$("#calendar").fullCalendar('refetchEvents');
}
});
Javascript (show the events)
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
businessHours: true, // display business hours
events: function(start, end, timezone, callback) {
$.post('<?php echo base_url(); ?>cCalendar/geteventos',
{ "start": start.format("YYYY-MM-DD"), "end": end.format("YYYY-MM-DD") },
function (data) {
callback($.parseJSON(data));
});
},
dayClick: function (date, jsEvent, view) {
date_last_clicked = $(this);
$('#modal_registrar').modal();
},
eventClick: function(event, jsEvent, view) {
$('#event_id').val(event.id);
$('#id_mot2').val(event.mot);
$('#nombre_estudiante').val(event.estudiante);
$('#jc2').val(event.jefe_c);
$('#rut_estudiante').val(event.rut_estudiante)
$('#start_f').val(moment(event.start).format('DD/MM/YYYY HH:mm:ss'));
$('#end_f').val(moment(event.end).format('DD/MM/YYYY HH:mm'));
$('#modal_editar').modal();
},
minTime: "08:30:00",
maxTime: "23:00:00"
});
when you run $("#calendar").fullCalendar('refetchEvents'); it runs another ajax call (the one defined in the calendar's events option), separate to the one you made explicitly from the "change" handler. You're throwing away the response from that call where you included rut_jc / rut_usu. You don't do anything with it. So it's no surprise it doesn't affect the calendar.
Instead of making a separate, meaningless ajax call, simply integrate this new functionality into your existing code:
Calendar Code
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
businessHours: true, // display business hours
events: function(start, end, timezone, callback) {
$.post('<?php echo base_url(); ?>cCalendar/geteventos', {
"start": start.format("YYYY-MM-DD"),
"end": end.format("YYYY-MM-DD"),
"rut_jc": $("#rut_jc").val() //add the extra value to the existing filter parameters. fullCalendar can then use it directly.
},
function(data) {
callback($.parseJSON(data));
}
);
},
dayClick: function(date, jsEvent, view) {
date_last_clicked = $(this);
$('#modal_registrar').modal();
},
eventClick: function(event, jsEvent, view) {
$('#event_id').val(event.id);
$('#id_mot2').val(event.mot);
$('#nombre_estudiante').val(event.estudiante);
$('#jc2').val(event.jefe_c);
$('#rut_estudiante').val(event.rut_estudiante)
$('#start_f').val(moment(event.start).format('DD/MM/YYYY HH:mm:ss'));
$('#end_f').val(moment(event.end).format('DD/MM/YYYY HH:mm'));
$('#modal_editar').modal();
},
minTime: "08:30:00",
maxTime: "23:00:00"
});
Change handler for the <select>
$("#rut_jc").change(function(){;
$("#calendar").fullCalendar('refetchEvents');
});
Additionally, you weren't passing the $rut_usu value to your model (instead, you just sent it back in the response, which made no sense).
N.B. I have also taken the liberty of adding the start/end dates sent by fullCalendar into your controller and model. As I mentioned in my answer to your earlier question a few days ago, you now need to alter your database query with another WHERE clause to ensure it only returns events which start or end between these two dates (inclusive).
Controller
public function geteventos(){
$start = $this->input->post('start');
$end = $this->input->post('end');
$rut_usu = $this->input->post('rut_jc');
$r = $this->mCalendar->geteventos($start, $end, $rut_usu);
echo json_encode($r);
}
Model
public function geteventos($start, $end, $rut_usu){
//...etc

Fetching events on FullCalendar

I'm trying to make FullCalendar works on my app, but I'm not able to fetch the events I have on my mysql database. Here is my code:
.cshtml
<div class="panel-body">
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
height: 600,
width: 500,
theme: false,
fixedWeekCount: false,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay',
},
weekends: false,
editable: false,
eventSources: [
'Agenda/getEvents'
],
});
});
</script>
<div id="calendar"></div>
</div>
.cs controller
{
public class AgendaController : Controller
{
// GET: Agenda
public ActionResult Index()
{
return View();
}
public ActionResult Agenda()
{
ViewBag.id = Session["id"];
ViewBag.usuario = Session["usuario"];
ViewBag.tipo_usuario = Session["tipo_usuario"];
return View();
}
[HttpPost]
public JsonResult getEvents(double start, double end)
{
try
{
DataTable dt = new DataTable();
using (MySqlConnection con = new MySqlConnection(BD.CadConMySQL()))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT tareas.tipo as title, tareas.fecha_inicio as start, tareas.fecha_fin as end FROM tareas", con))
{
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return Json(dt.ToList());
}
catch (Exception e)
{
RespGeneric resp = new RespGeneric("KO");
resp.msg = e.Message;
return Json(resp);
}
}
So the Agenda/getEvents give me back this following JSON that seems ok for FullCalendar:
JSON
However, the calendar doesnt show any event and I dont get why because the JSON looks good and if I fetch the events one by one on the .cshtml with exactly the same data it works.
Thanks!
I think that you didn't respect the structure of a standard eventSource fetch which is described in the documentation as :
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: '/myfeed.php',
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});

Event not being limited

Hello guys I'm using full calendar for my calendar. The problem I'm facing right now is I'm populating all of the events in my calendar. Now for instance if I have 10 events on a day it will all those events rather then showing 4 events and then giving a plus event to see all the other event. I can't understand why am I facing this problem. Please tell me what is it that I'm doing wrong. Here is the code through which I'm populating my event:
viewRender: function (view) {
$.ajax({
type: "POST",
url: base_url +"apps/calendar/getByMonth",
async : false,
dataType: 'html',
data: {'type': $('#formName').val() },
success: function(mark_up){
mark_up = JSON.parse(mark_up);
$.each(mark_up["task"], function() {
this.start = this.end;
});
my_events = mark_up["task"];
console.log(my_events);
$('#calendar').fullCalendar( 'removeEvents');
$('#calendar').fullCalendar('addEventSource', my_events);
}
});
}
When the calendar then I make a ajax call to get all the events and then assign those events to my_events.
Use below parameter in your fullcalendar configuration
$('#calendar').fullCalendar({
eventLimit: 4, // Here
viewRender: function (view) {
// Your code mentioned in your question.
}
});
This is just an example to place eventLimit.
This works for me.
It's the full calendar default.
see
http://fullcalendar.io/docs/display/eventLimit/
eventLimit 2.1.0 Limits the number of events displayed on a day.
Boolean, Integer. default: false
Usage
$('#calendar').fullCalendar({
eventLimit: true, // for all non-agenda views
views: {
agenda: {
eventLimit: 6 // adjust to 6 only for agendaWeek/agendaDay
}
}
});
Just use it as false.
I don't know which version you'r using, but it's strange that it isn't false as default.

AngularJS and Fullcalendar: eventClick works only first time

I'm using the Angular module based on fullcalendar: https://github.com/angular-ui/ui-calendar along with the dialog module from ng-bootstrap. I configured the calendar to show a dialog for editing an event on eventClick action. It works fine only once. After closing first dialog and clicking again on any event new dialog doesn't show. But when I click on any other link on page, all desired dialogs shows one by one like they're queued somewhere some way.
Here's snippet from my controller:
$scope.showEditVisitDialog = function (event) {
var editVisitDialogOpts = {
backdropClick: false,
templateUrl: 'views/addEditVisitDialog.html',
controller: 'AddEditVisitDialogController',
resolve: {
patientId: function () {
return event.patientId;
},
visitId: function () {
return event.id;
}
}
};
var editVisitDialog = $dialog.dialog(editVisitDialogOpts);
editVisitDialog.open().then(function (updatedVisit) {
//some action
});
};
$scope.calendar = {
height: 450,
editable: true,
header: {
left: 'month agendaWeek ',
center: 'title',
right: 'today prev,next'
},
eventClick: $scope.showEditVisitDialog
};
$scope.events = [];
$scope.eventSources = [$scope.events]
Events are fetched from REST later in the controller.
In html:
<div ui-calendar="calendar" config="calendar" ng-model="eventSources"/>
No errors in console, what am I doing wrong?
Code on plunker: http://plnkr.co/edit/89sQfsU85zN4uxauFI2Y?p=preview
As always, things are simpler and more obvious when there's a fiddle/plnkr available. You need to place your call to showEditVisitDialog inside the $apply function:
...
$scope.calendar = {
editable: true,
eventClick: function(){
$scope.$apply(function(){
$scope.showEditVisitDialog()
});
}
};
...
Working plnkr.
you need to declare you fnction before uiConfig for the calendar ;)

Categories