I am using fullCalendar plugin to display events from ASP.NET ASMX web service. JSON data is fetched correct and displayed ok in the console. But events are not rendered on the calendar view. What am I missing?
$('#divcalendar').fullCalendar({
defaultDate: '2018-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function (start, end, timezone,callback) {
$.ajax({
type: "POST",
url: 'Webservice.asmx/ListEvents',
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var event = [];
$(data.d).each(function () {
event.push({
title: this.Title,
start: this.Start,
end: this.End
});
});
console.log(event);
callback(event);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('There was an error');
}
});
}
});
[WebMethod]
public CalendarEvent[] ListEvents()
{
DateTime epoc = new DateTime(1970, 1, 1);
return new CalendarEvent[]
{
new CalendarEvent { Title = "Event 1", Start = new DateTime(2018,3,9,16,0,0).Subtract(epoc).TotalSeconds, End = new DateTime(2018,3,9,17,0,0).Subtract(epoc).TotalSeconds},
new CalendarEvent { Title = "Event 2", Start = new DateTime(2018,3,12,12,0,0).Subtract(epoc).TotalSeconds, End = new DateTime(2018,3,12,13,0,0).Subtract(epoc).TotalSeconds}
};
}
Console output from webservice
{"d":[{"__type":"CalendarEvent","End":1520614800,"Start":1520611200,"Title":"Event 1"},{"__type":"CalendarEvent","End":1520859600,"Start":1520856000,"Title":"Event 2"}]}
I think your dates are being entered into the calendar, but not in the place you intended.
Although you haven't mentioned it explicitly, I would strongly suspect that the timestamps you're outputting for your start and end dates are specified in seconds.
Now, fullCalendar uses momentJS to parse any date strings or timestamps supplied to it. Alternatively it can accept ready-made momentJS or JS Date objects.
momentJS can parse timestamps automatically through the momentJS constructor (which fullCalendar is calling when it receives your timestamp value), but it assumes the value is given in milliseconds, not seconds.
Therefore when you supply it with, for instance, 1520611200 (the start date of your first event), it interprets that in milliseconds and the resulting date is 1970-01-18 14:23:31.
If you want to specify the date in seconds you have to use the moment.unix() method instead. Using this method, your timestamp is instead interpreted as 2018-03-09 16:00:00, which I assume is what you intended.
See http://jsfiddle.net/Loccoxds/1/ for a demo to see the difference in how momentJS parses one of your values.
To get your code working, the simplest way is to do this:
success: function (data) {
var event = [];
$(data.d).each(function () {
event.push({
title: this.Title,
start: moment.unix(this.Start),
end: moment.unix(this.End)
});
});
console.log(event);
callback(event);
},
This way, you supply a ready-made momentJS object to fullCalendar, having correctly parsed the timestamp.
See http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/ for more details about parsing timestamps in momentJS
P.S. Alternatively of course you could change your asmx service to output the dates in a format momentJS can parse automatically, such as a timestamp in milliseconds, or an ISO8601-formatted date string - see http://momentjs.com/docs/#/parsing/string/ for details of that.
P.P.S. ASMX is pretty much a legacy technology within .NET now. You should consider using WCF or Web API instead. Microsoft recommends not to create new code using ASMX.
Related
i am new developer and i want to make an app in cakephp 3.7 thas uses jquery full calendar plugin for reservations.In my database is stored a specific date range (starting date and ending date fields).I want to use this date range in my calendar so that if a user clicks on a specific day on the callendar that is out of this date range, the app will display a messange informing the user that he cannot make a reservation for that day!
Any useful suggestions on who i will handle on this ??
Thank you!!
I have done it using the cakephp 3.6.
Generic steps that you would follow:
You will include your full calendar js and jquery in the 'full
calendar' template
Then initialise your fullcalendar. Now you should see the calendar.
Once done, from the fullcalendar make an ajax call to your controller to get the events. eg.
var fcSources = {
loadEvents: {
url: //your controller action,
type: "GET",
cache: true,
timezone: "Europe/London",
className: "events",
dataType: "json",
success: function (data) {
return data.events;
}
},
}
Later part can be done by simply checking the date value against current date.
I would like to ask about datepicker. I am currently developing a website where university students have to pick their own Thursday to hear a talk about career.
First of all, I have managed to disable all days except Thursday. The code I wrote stated below :
<script>
$( function()
{
$( "#datepicker" ).datepicker({dateFormat: 'yy-mm-dd', minDate: 0, maxDate:
'2018-12-15', beforeShowDay: function(date){var day = date.getDay();return
[day == 4,'disable'];
}});
} );
</script>
But now I would to disable a certain Thursday for example next Thursday which is:
'yy-mm-dd' = '2017-08-17'
Can someone explain to me how or where should I do the modification to the code which can allow me to disable a certain Thursday?
Refer this image for my datepicker https://drive.google.com/file/d/0ByJlnNeKIynkQ3IzRTN2cHg4WFE/view?usp=sharing
Use like this:
Date.getDay() returns a value in the range 0-6, not 1-7.
beforeShowDay: function(date) {
return [date.getDay() === 0,''];
}
you can still use the onBeforeShowDay, since it will get called before the datepicker is displayed, because changing months will make the datepicker to render again.
You can use an array that stores the list of dates and change this based on the result from your ajax call. e.g:
//at first only september dates will be disabled.
var array = ["2017-08-10","2017-08-17","2017-08-24"];
$('input').datepicker({
onChangeMonthYear: function(year, month, inst) {
// Perform AJAX call and get the list
//override the array, and now the october dates will be disabled.
$.ajax({
url: ajaxUrl,
type: "post",
data: serializedData,
async: false,
success: function (data) {
array = data; //["2017-08-10","2017-08-17","2017-08-24"];
}
});
},
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [array.indexOf(string) == -1 ]
}
});
I'm using eventSources method to initialize FullCalendar jQuery plugin.
eventSources: [
initEvents(visibleStartDate, visibleEndDate)
]
where initEvents is and ajax call to jsp page that returns json object representing events to be rendered. It works great but now I'd like to fetch the event only for the dates visible on calendar. I read in documentation that I could use visStart and visEnd on View object to get the start and end day of the calendar, however I don't know how to get that information at the time I initialize my eventSources. Is there a way? Thank you in advance for your responses.
Eric
It turns out that fullcalendar plugin will add start and end HTTP parameters when calendar sources are fetched externally. Full details are described in documentation here: http://arshaw.com/fullcalendar/docs/event_data/events_json_feed/
My code (mix of javascript, JSP, JSF):
FullCalendal initialization:
page.view.calendar.fullCalendar(
{
....
eventSources: [
page.control.initEventSources(#{sessionBean.myCalendar.calendarConfgIdNbr},'Approved'),
page.control.initCalendarHolidays(#{sessionBean.myCalendar.calendarConfgIdNbr})],
....
});
2. My javascript function:
page.control.initEventSources:
var page = {
control : {
initEventSources : function(calConfId, status) {
return {
url: '/oceportal/tom/data/bookings.jsp',
type: 'POST',
data: { calConfId: calConfId, bookingStatus: status, loggedInId: "#{sessionBean.loggedInId}", },
success: function(data) { },
error: function() { alert('there was an error while fetching events!'); },
color: 'none',
textColor: page.colorConfig[status]
};
}
}
}
My JSP snippet (to retrieve first and last visible day):
String start = request.getParameter("start");
Date startDt = new Date(Long.parseLong(start)*1000);
String end = request.getParameter("end");
Date endDt = new Date(Long.parseLong(end)*1000);
Hope it helps someone.
When the Action method below attempts to return the Json result no data object comes back to the $.ajax function. Hence I presume I am not serializing the arrays prior to sending them off as a Json result. I need to retain the array names i.e: ProgTypes, Ages etc. So I know which array is which when the data returns from the server.
$.ajax({
url: '/Education/FilterLists',
dataType: 'json',
data: { svalues: svalues, firsttype: $firsttype },
traditional: true,
success: function (data) {
//do something with data
alert('done');
}
});
..
public JsonResult FilterLists(int[] svalues, string firsttype)
{
//Some logic takes place and below arrays are produced
int[] ProgTypes = programs.Select(x => x.FilterValToCatMaps.FirstOrDefault(c => c.FilterValue.FilterID == 5).FilterValueID).Distinct().ToArray();
int[] Ages = programs.Select(x => x.FilterValToCatMaps.FirstOrDefault(c => c.FilterValue.FilterID == 4).FilterValueID).Distinct().ToArray();
int[] Countries = programs.Select(x => x.ParentCategory.ParentCategory.ParentCategory.CatID).Distinct().ToArray();
return Json(new { progtypes = ProgTypes, ages = Ages, countries = Countries});
}
You are attempting to retrieve JSON data via a GET request (jQuery AJAX implicitly does a GET unless you specify the "type: 'POST'" option"). ASP.NET blocks JSON returning GETs for security reasons with an exception of this message:
"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."
Your success function is never getting executed because the request isn't a success. I would recommend getting FireBug for FireFox and using the 'Net' tab or use chromes built in debugger and use the 'Network' tab if you are going to be doing any web development (especially AJAX). Network errors pop right up in there and it can save you a lot of time.
You have two options at this point, change your .NET code or change your JavaScript, pick one below:
$.ajax({
url: '/Education/FilterLists',
dataType: 'json',
type: 'POST', //ADD POST HERE
data: { svalues: svalues, firsttype: $firsttype },
traditional: true,
success: function (data) {
//do something with data
alert('done');
}
});
OR
return Json(new { progtypes = ProgTypes, ages = Ages, countries = Countries}, JsonRequestBehavior.AllowGet);
I am trying to design a cascading dropdown. i am using 3 asp.net dropdowns. THe first one on page load loads the countries. Then when a country is selected i do a ajax call to a webmethod. I fetch the data for the teams belonging to that country. The data is in a dataset which i convert into JSON and then return it. On success what code do i need to add to bind the json data to the dropdown list.
below is the code.
$(document).ready(function() {
$('#ddlcountries').change(function() {
debugger;
var countryID = $('#ddlcountries').val();
$.ajax({
type: "POST",
url: "Default.aspx/FillTeamsWM",
data: '{"CountryID":' + countryID + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(jsonObj) {
/* WHAT CODE DO I ADD HERE TO BIND THE JSON DATA
TO ASP.NET DROP DOWN LIST. I DID SOME GOOGLING
BUT COULD NOT GET PROPER ANSWER */
},
error: function() {
alert('error');
}
});
});
});
Depending on what you're passing back to the client, I am going to assume it's a List<string>. You can adjust the code accordingly depending on what you're passing back to the client, since you're not telling us what is being passed back.
So if that is the case do something like this:
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item).html(item));
});
Assuming again, if your List has an object containing teamid and `teamname11
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item.teamid).html(item.teamname));
});
It is dependent on the data you are getting back from the server but this is what I came up with presuming it was a simple json structure, I was also wondering whether it may be better to send the data on the first request, and forget about the ajax.
$('#continent').change(function() {
// success function
$('#country').children().remove();
for (var country in json.continents[$(this).val()]) {
var $elm = $('<option>').attr('value', country)
.html(country);
$('#country').append($elm);
}
})
Here is a demo;
Edit: Given your data structure have update so something like this
var teams = json['TeamList'];
$('#teamid').change(function() {
// success function
var $t = $(this);
var $select = $('#teamname');
var i = (function() {
for (var i=0; i<teams.length; i++) {
if (teams[i]['teamid'] == $t.val()) {
return i;
}
}
})()
var name = teams[i]['teamname'];
var $elm = $('<option>').val(name).html(name);
$select.children().remove();
$select.append($elm);
})
see here for demo, please note this may requiring some changing to fit your specific use case, but it demonstrates simple iteration over arrays and objects