Database with time in fullcalendar Not working - javascript

We are saved FromTime and ToTime value from database below attached image:
var events = [];
$.ajax({
type: "GET",
url: "/Booking/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.EventName,
description: v.Description,
start: moment(v.BookedFromDate).moment(v.FromTime),
end: v.BookedToDate != null ? moment(v.BookedToDate) : null,
name: v.ParticipantName,
className: 'event-red'
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
In this Code i need to get FromTime Value but in my code not working..
start: moment(v.BookedFromDate).moment(v.FromTime),
I need to display date and time

Related

How to call events method after new event source in FullCalendar.js?

I am trying to create a client side filter for events, I have gone with the same approach of addEventSource. I use the events method to conditionally render the events. I just wanna know how to call the events method or even redefine it?
This is the initial code I am using to render the the calendar
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
displayEventTime: false,
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
events: (start, end, timezone, callback) => {
$.ajax({
url: 'get-events',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function (res) {
console.log(res)
var events = [];
res.map((value, index) => {
if (value.cadence != null) {
$("#allDropdown").append(`<a id="file-${value.dq_datafile_id}" onclick="selectThis(this)" href="#about">${value.data_file_name}</a>`)
}
if (value.cadence == "WEEKLY") {
if (value.dqfeed__file_status == "RECEIVED") {
const data_file_name = value.data_file_name;
let repeatDay = dow_handler.hasOwnProperty(data_file_name) ? dow_handler[data_file_name] : undefined
events.push({
title: `${value.data_file_name}`,
start: '2020-04-13',
dow: [repeatDay, 1],
color: '#00ff00'
});
}
});
});
});
This is the code I am using to fetch new events or filtered events
const applyCalendarFilter = () => {
var filter = {
type: 'get',
url: 'filter-events',
}
$("#calendar").fullCalendar('addEventSource', filter);
}
The error I get is Uncaught TypeError: Cannot read property 'hasTime' of undefined because the JSON returned doesn't have a start_date or end_date
So I found removeEvents that will clear all the events from the calendar and renderEvents that takes an option argument events and this will render the rest of the events.
So here's the code that did this.
const applyCalendarFilter = () => {
var filter = {
type: 'get',
url: 'filter-events',
}
$("#calendar").fullCalendar('removeEvents');
$.ajax({
url: 'filter-events',
type: 'get',
success: (res) => {
let events = [];
res.map((value, index) => {
if (value.cadence == "WEEKLY"){
events.push({
'title': value.title,
'start_date': value.start_date,
'end_date': value.end_date
}
})
$("#calendar").fullCalendar('renderEvents', events);
}, error: (res) => {
alert('cant get the data');
}
)};

Fullcalendar - can't get events to show asp.net

I'm trying to implement fullcalender but I can't get the exemple data to show. I have been following this guide.
I get no errors but the events doesn't show in the calendar. I have tried different solutions but I can't get it to work, also my experience with json is very limited and i would appreciate some help.
public class CalendarController : BaseController
{
public ActionResult ShowCalendar()
{
return View();
}
public ActionResult GetMeetings(double start, double end)
{
using (var db = new ApplicationDbContext())
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var eventList = GetEvents();
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
private List<Events> GetEvents()
{
List<Events> eventList = new List<Events>();
Events newEvent = new Events
{
id = "1",
title = "Event 1",
start = DateTime.Now.AddDays(1).ToString("s"),
end = DateTime.Now.AddDays(1).ToString("s"),
allDay = false
};
eventList.Add(newEvent);
newEvent = new Events
{
id = "1",
title = "Event 3",
start = DateTime.Now.AddDays(2).ToString("s"),
end = DateTime.Now.AddDays(3).ToString("s"),
allDay = false
};
eventList.Add(newEvent);
return eventList;
}
<head>
#section scripts{
<link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
<script src='lib/jquery.min.js'></script>
<script src='lib/moment.min.js'></script>
<script src='fullcalendar/fullcalendar.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev, next, today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
buttonText: {
prev: '<',
next: '>'
},
defaultView: 'month',
editable: false,
weekMode: 'liquid',
//allDaySlot: false,
selectTable: true,
//slotMinutes: 15,
events: function (start, end, timezone, callback) {
$.ajax({
url: "/calendar/getmeetings/",
type: 'GET',
dataType: 'json',
success: function (start, end, timezone, callback) {
alert('success');
},
error: function (start, end, timezone, callback) {
alert('there was an error while fetching events!');
},
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
}
});
}
});
});
</script>
}
</head>
<br />
<div class="jumbotron">
<h1>Event Calendar</h1>
<div id="calendar"></div>
</div>
You are not following the tutorial particularly closely, I note, and are using a different methodology to fetch the events.
Within that, you simply forgot to pass the event list back to fullCalendar. You need to execute the callback function which fullCalendar provided to you, and supply your events to it.
Your definition of "success" and "error"'s callback parameters are nonsense, btw - you need to check the jQuery $.ajax documentation (http://api.jquery.com/jquery.ajax/) to see what is provided:
success: function (response) { //response will contain the JSON data from the server
callback(response); //pass the data to fullCalendar. You can pass "response" directly, assuming the response directly contains a JSON array of events
},
error: function(jqXHR) {
alert(jqXHR.responseText);
}
See https://fullcalendar.io/docs/event_data/events_function/ for more details.
You are not passing the events in a right way try passing the events my way its simple.If in case u still didn't get the calendar u need to check the console for some exception. Before passing the events u need the push the data to events.
event_array.push({
userid: v.UserId,
start: moment(v.LoginTime),
//end: moment(v.LogoutTime)
//start: moment(v.start),
end: v.LogoutTime != null ? moment(v.LogoutTime) : null
//color: v.themecolor,
//allday: v.isfullday
});
and then u need to call that in calender id for example
function GenerateCalender(event_array) {
debugger;
//$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
events: event_array
});
}
This is my full code-
var event_array = [];
var event_array = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
url: "/Home/GetEvents",
data: "",
type: "GET",
dataType: "json",
async: false,
cache: false,
success: function (data) {
alert("success");
$.each(data, function (i, v) {
event_array.push({
userid: v.UserId,
start: moment(v.LoginTime),
//end: moment(v.LogoutTime)
//start: moment(v.start),
end: v.LogoutTime != null ? moment(v.LogoutTime) : null
//color: v.themecolor,
//allday: v.isfullday
});
})
GenerateCalender(event_array);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(event_array) {
debugger;
//$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
events: event_array
});
}

Select2 returns TypeError: data is undefined

I'm trying to get Select2 working with Rails. I have the API endpoint working but I get a TypeError: data is undefined message in my console, so the select fields aren't being populated.
My code looks like this:
$(document).ready(function() {
return $('#form_emails').select2({
placeholder: 'User list',
minimumInputLength: 3,
ajax: {
url: '/api/s/users',
dataType: 'json',
quietMillis: 250,
data: function(term) {
return { q: term };
},
results: function(data) {
var results;
results = [];
$.each(data, function(idx, item) {
results.push({
'id': item.id,
'text': item.first_name + ' ' + item.last_name
});
});
return { results: results };
}
}
});
});
Any idea why I might be getting the aforementioned error? Thanks in advance!
According to Select2 documentation the function where you can transform data from Ajax request is named processResults, not results.
See: https://select2.org/data-sources/ajax#transforming-response-data
So the correct code should be:
$(document).ready(function() {
return $('#form_emails').select2({
placeholder: 'User list',
minimumInputLength: 3,
ajax: {
url: '/api/s/users',
dataType: 'json',
quietMillis: 250,
data: function(term) {
return { q: term };
},
processResults: function(data) {
var results;
results = [];
$.each(data, function(idx, item) {
results.push({
'id': item.id,
'text': item.first_name + ' ' + item.last_name
});
});
return { results: results };
}
}
});
});

How to populate extra fields with jQuery autocomplete

I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}

Uncaught TypeError: Object has no method autocomplete and its blocking to populate dialogue box to delete

I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});

Categories