Here is the ajax code, am doubting the resource section because it has 645 data's in the array. when i put small amount of static data's it works. Chrome, firefox and safari works fin only in IE it takes time to generate the calendar.
any one can help me on this please.
//get vehicle to calendar
$.ajax({
method: "GET",
url: '#Url.Action("WP", "WeeklyPlan")',
cache: false,
data: {
}, success: function (data) {
resource = []
events = []
var vehiclesWithReserations = data.vehicles;
if (vehiclesWithReserations == null) {
hideLoader();
toastr.warning(data.message);
return;
} else if (vehiclesWithReserations.length == 0) {
hideLoader();
}
var holidayList = data.holidays;
$.each(vehiclesWithReserations, function (i, v) {
resource.push({
id: v.FuhrparkFahrzeugID,
title: v.ModellName,
field: v.LocationId,
zuteilung: v.ZutName,
nvx: v.NVX
});
for (var q = 0; q < v.Reservations.length; q++) {
events.push({
id: v.Reservations[q].ReservationID,
resourceId: v.FuhrparkFahrzeugID,
start: moment(v.Reservations[q].DateFrom).toDate(),
end: moment(v.Reservations[q].DateTo).toDate()
})
}
});
generatecalender(holidayList);
}
Related
I have a ajax call to get attendance of student and returns larger amount of rows (0 - 1,000,000). When 1,000 row exceed browser will fall to 'Out of Memory' error. Also, I need to display the all record on the same page. How can I approch this functionality?
My controller
public JsonResult GetAttendance(int StudentID, int OffSet)
{
var attendanceRecords = mUnitOfWork.StudentAttendanceRepository.GetAll(a => a.StudentID == StudentID, OffSet).ToList();
var jsonResult = Json(attendanceRecords.Select(a => new
{
Date = a.AttendanceDate,
AbsentOrPresent = (bool)a.AbsentOrPresent,
}), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
Java script code:
var NoOfRecords = 124512; //student attendance record count taken to here
var OffSet = 0;
var Limit = 1000;
function LoadAttendanceRecords() {
$.ajax({
url: $("#GetAttendance").val(),
type: "POST",
dataType: "JSON",
data: {
StudentID: $("#StudentID").val(),
OffSet: OffSet;
},
success: function(result) {
$.each(result, function(i, o) {
var row = $('#tableAttendance tbody>tr:last').clone(true);
$('label[name="Date"]', row).val(o.Date);
$('label[name="Presence"]', row).val(o.AbsentOrPresent);
$('#tableAttendance tbody').append(row);
}
});
OffSet += Limit;
if (OffSet < NoOfRecords) {
LoadAttendanceRecords();
}
});
}
I've a calendar that I want to list various types of event on and enable a checkbox filter to show/hide those kind of events.
Is there a way to say on this action, ONLY load from 1 data-source AND remember that URL on month next/prev links?
I've started using eventSources, but it loads them all, rather than the one(s) I want.. Here's what I have.
var fcSources = {
all: {
url: tournament_url + '/getCalendar/?typefilter=[1,2]'
},
type1: {
url: tournament_url + '/getCalendar/?typefilter=[1]'
},
type2: {
url: tournament_url + '/getCalendar/?typefilter=[2]'
}
};
These URLS all provide a json string of events, based on the types prrovided.
Here's my calendar:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek'
},
firstDay: 1, // Monday = 1
defaultDate: new Date(), // Now
editable: true,
eventSources: [ fcSources.all ],
events: fcSources.all,
nextDayThreshold: '00:00:00',
... etc etc
Above my calendar I have this:
input type="checkbox" name="event_filter[]" value="type1" /> Type 1
input type="checkbox" name="event_filter[]" value="type2" /> Type 2
And finally , two Jquery fucntions.. one to get all the filters:
function getFilters(getName) {
var filters = [];
var checked = [];
$("input[name='"+getName+"[]']").each(function () {
filters.push( $(this).val() );
});
$("input[name='"+getName+"[]']:checked").each(function () {
checked.push( $(this).val() );
});
return [filters, checked];
}
and the last to load them:
$(".event_filter").on('click', function() {
var doFilters = getFilters('event_filter');
$('#calendar').fullCalendar( 'removeEvents' );
if (doFilters[0] === doFilters[1]) {
$('#calendar').fullCalendar( 'addEventSource', fcSources.all );
} else {
$.each(doFilters[1], function(myFilter, myVal) {
console.log(myVal);
$('#calendar').fullCalendar( 'addEventSource', fcSources.myVal );
});
}
// $('#calendar').fullCalendar( 'refetchEvents' );
});
Since the sources are all the same place and just different data on the URL, this approach could meet your needs. In the demo it just alerts the URL that is being tried but doesn't actually supply any data...
https://jsfiddle.net/gzbrc2h6/1/
var tournament_url = 'https://www.example.com/'
$('#calendar').fullCalendar({
events: {
url: tournament_url + '/getCalendar/',
data: function() {
var vals = [];
// Are the [ and ] needed in the url? If not, remove them here
// This could (should!) also be set to all input[name='event_filter[]'] val's instead of hard-coded...
var filterVal = '[1,2]';
$('input[name="event_filter[]"]:checked').each(function() {
vals.push($(this).val());
});
if (vals.length) {
filterVal = '[' + vals.join(',') + ']' // Are the [ and ] needed in the url? If not, remove here too
}
return {
typefilter: filterVal
};
},
beforeSend: function(jqXHR, settings) {
alert(unescape(settings.url));
}
}
});
// when they change the checkboxes, refresh calendar
$('input[name="event_filter[]"]').on('change', function() {
$('#calendar').fullCalendar('refetchEvents');
});
Try this!
$('#calendar').fullCalendar({
events: function( start, end, timezone, callback ) {
var checked = [];
$("input[name='event_filter[]']:checked").each(function () {
checked.push( $(this).val() );
});
var tournament_url = 'https://www.example.com';
$.ajax({
url: tournament_url + '/getCalendar/',
data: {typefilter: '['+checked.join(',')+']'},
success: function(events) {
callback(events);
}
});
}
});
$('input[name="event_filter[]"]').on('change', function() {
$('#calendar').fullCalendar('refetchEvents');
});
This works for me.
Here, my javascript code to render markers in map and after that fitBounds of that map.
Map bounds are get fit according to geojson, but problem is that when there is any marker
on map and I try to fit bound, map tiles images are not get render.
In map it display only markers, no tile images.
var latLongCollection = [];
var map;
$(document).ready(function() {
map();
});
function map() {
map = L.mapbox.map('DivId', 'ProjectId');
GetData();
}
function GetData() {
$.ajax({
type: "GET",
url: someUrl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: AjaxSuccess,
error: function () {
}
});
}
function AjaxSuccess(data) {
if (data == null || data.length == 0) {
return;
}
var geoJson = {
"type": "FeatureCollection",
"features": []
};
$.each(data, function (index, value) {
var latitude = parseFloat(value.Latitude),
longitude = parseFloat(value.Longitude);
if (latitude && longitude) {
var dataJson = {
type: "Feature",
geometry: { type: "Point", coordinates: [longitude, latitude] },
properties: {
someProp: value.SomeProperty,
}
};
geoJson.features.push(vehicleJson);
}
});
var markerLayer = L.mapbox.featureLayer(geoJson).addTo(map);
markerLayer.eachLayer(function (marker) {
var feature = marker.feature;
var featureProperty = feature.properties;
if (featureProperty.someProp) {
marker.setIcon(L.divIcon({
html: 'htmlstring',
iconSize: [35, 75]
}));
}
else {
marker.setIcon(L.divIcon({
html: 'anotherhtmlstring',
iconSize: [35, 75]
}));
}
latLongCollection.push(marker._latlng);
});
markerLayer.on('click', function (e) {
map.panTo(e.layer.getLatLng());
});
if (latLongCollection.length > 0) {
map.fitBounds(latLongCollection);
}
}
If anyone is still struggling with this, it appears to be a bug in Leaflet: https://github.com/Leaflet/Leaflet/issues/2021
It has been fixed in the latest version, but if you can't update you can work around the race condition by setting a timeout:
setTimeout(function () {
map.fitBounds(latLongCollection);
}, 0);
How did you try debug the problem? What's your network and js console saying?
Try to zoom out, maybe fitBounds zooms your map too much. I had this problem. The solution was using maxSize option in fitBounds, see leaflet docs.
I have a Kendo UI grid and a Kendo UI Window on the same page. The window contains form elements for record insertion, a record being represented by a row in the grid. But for reasons not known by me, when I opened the window and closed it again and then reopened, Kendo UI scaled it to be 100x smaller. I didn't want to hack the window, so I've looked for alternative solution.
I've used jQuery 1.7.2. I've updated jQuery to version 1.8.0. and window opening, closing and reopening worked. I was very happy until I realized that now the grid filters are not working. When I click on a grid filter, nothing happens, no popup, nothing. What is the cause of this and what would be the solution?
EDIT:
This is my code (I've replaced the values of the Urls). Grid filters are working with jQuery 1.7.2. and window reopen works with new versions of jQuery. Also, if I remove the sort hack, the grid filter popup still doesn't show up.
var hshflt = {};
var addWindow;
var editWindow;
var init = false;
//Sort Hack
/*
Changes all dataSources to case insensitive sorting (client side sorting).
This snipped enable case insensitive sorting on Kendo UI grid, too.
The original case sensitive comparer is a private and can't be accessed without modifying the original source code.
tested with Kendo UI version 2012.2.710 (Q2 2012 / July 2012).
*/
var CaseInsensitiveComparer = {
getterCache: {},
getter: function (expression) {
return this.getterCache[expression] = this.getterCache[expression] || new Function("d", "return " + kendo.expr(expression));
},
selector: function (field) {
return jQuery.isFunction(field) ? field : this.getter(field);
},
asc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a > b ? 1 : (a < b ? -1 : 0);
};
},
desc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a < b ? 1 : (a > b ? -1 : 0);
};
},
create: function (descriptor) {
return this[descriptor.dir.toLowerCase()](descriptor.field);
},
combine: function (comparers) {
return function (a, b) {
var result = comparers[0](a, b),
idx,
length;
for (idx = 1, length = comparers.length; idx < length; idx++) {
result = result || comparers[idx](a, b);
}
return result;
};
}
};
kendo.data.Query.prototype.normalizeSort = function (field, dir) {
if (field) {
var descriptor = typeof field === "string" ? { field: field, dir: dir} : field,
descriptors = jQuery.isArray(descriptor) ? descriptor : (descriptor !== undefined ? [descriptor] : []);
return jQuery.grep(descriptors, function (d) { return !!d.dir; });
}
};
kendo.data.Query.prototype.sort = function (field, dir, comparer) {
var idx,
length,
descriptors = this.normalizeSort(field, dir),
comparers = [];
comparer = comparer || CaseInsensitiveComparer;
if (descriptors.length) {
for (idx = 0, length = descriptors.length; idx < length; idx++) {
comparers.push(comparer.create(descriptors[idx]));
}
return this.orderBy({ compare: comparer.combine(comparers) });
}
return this;
};
kendo.data.Query.prototype.orderBy = function (selector) {
var result = this.data.slice(0),
comparer = jQuery.isFunction(selector) || !selector ? CaseInsensitiveComparer.asc(selector) : selector.compare;
return new kendo.data.Query(result.sort(comparer));
};
kendo.data.Query.prototype.orderByDescending = function (selector) {
return new kendo.data.Query(this.data.slice(0).sort(CaseInsensitiveComparer.desc(selector)));
};
//Sort Hack
$("#refresh-btn").click(function () {
refreshGrid();
});
var grid;
function getPageIndex() {
if (!(grid)) {
return 0;
}
return grid.pager.page() - 1;
}
function getPageSize() {
if (!(grid)) {
return 10;
}
return grid.pager.pageSize();
}
function getFilters() {
if (!(grid)) {
return "";
}
return grid.dataSource.filter();
}
function getSorts() {
if (!(grid)) {
return "";
}
var arr = grid.dataSource.sort();
if ((arr) && (arr.length == 0)) {
return "";
}
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in grid.columns) {
if (grid.columns[col].field === arr[index].field) {
type = grid.columns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
function getColumns() {
if (!(grid)) {
return "";
}
var columns = "";
for (var col in grid.columns) {
if (columns.length > 0) {
columns += ";";
}
columns += grid.columns[col].field + "," + grid.columns[col].type;
}
return columns;
}
var initGrid = true;
var grid2Data;
function getDataSource() {
$.ajax({
type: 'POST',
url: 'mydsurl' + getParams(),
data: "filter=" + JSON.stringify(getFilters()) + "&columns=" + getColumns(),
success: function (param) { grid2Data = param; },
//dataType: dataType,
async: false
});
return grid2Data.Data;
}
var shouldClickOnRefresh = false;
function refreshGrid() {
shouldClickOnRefresh = false;
$.ajax({
type: 'POST',
url: 'mydsurl' + getParams(),
data: "filter=" + JSON.stringify(getFilters()) + "&columns=" + getColumns(),
success: function (param) { grid2Data = param; },
//dataType: dataType,
async: false
});
grid.dataSource.total = function () {
return grid2Data.Total;
}
for (var col in grid.columns) {
if ((grid.columns[col].type) && (grid.columns[col].type === "Date")) {
for (var row in grid2Data.Data) {
grid2Data.Data[row][grid.columns[col].field] = new Date(parseInt((grid2Data.Data[row][grid.columns[col].field] + "").replace("/Date(", "").replace(")/", "")));
}
}
}
grid.dataSource.data(grid2Data.Data);
shouldClickOnRefresh = true;
}
function getParams() {
return getPageSize() + "|" + getPageIndex() + "|" + getSorts();
}
function bindGrid() {
var editUrl = 'myediturl';
if (!(editWindow)) {
editWindow = $("#edit-window");
}
$(".k-button.k-button-icontext.k-grid-edit").each(function (index) {
$(this).click(function () {
if (!editWindow.data("kendoWindow")) {
editWindow.kendoWindow({
title: "Edit User",
width: "60%",
height: "60%",
close: onClose,
open: onEditOpen,
content: editUrl + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"]
});
}
else {
editWindow.data("kendoWindow").refresh(editUrl + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"]);
editWindow.data("kendoWindow").open();
}
editWindow.data("kendoWindow").center();
return false;
})
});
$(".k-button.k-button-icontext.k-grid-delete").each(function (index) {
$(this).click(function () {
var r = confirm("Are you sure you want to delete this user?");
if (r == true) {
$.ajax({
type: 'POST',
url: 'mydelurl' + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"],
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
});
});
}
function onDataBound() {
if (!(shouldClickOnRefresh)) {
shouldClickOnRefresh = true;
bindGrid();
}
else {
refreshGrid();
}
}
$(function () {
$("#grid").kendoGrid({
dataBound: onDataBound,
dataSource: {
autoSync: true,
data: getDataSource(),
serverPaging: true,
schema: {
model: {
fields: {
Email: { type: "string" },
FullName: { type: "string" },
LogCreateDate: { type: "date" },
RoleName: { type: "string" },
UserName: { type: "string" }
}
},
total: function (response) {
return grid2Data.Total;
}
},
pageSize: 10
},
toolbar: ["create"],
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false,
pageSizes: true
},
columns: [
{
command: ["edit", "destroy"],
title: " "
},
{
field: "Email",
title: "Email",
type: "String"
},
{
field: "FullName",
title: "Full Name",
type: "String"
},
{
field: "LogCreateDate",
title: "Created",
type: "Date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
},
{
field: "RoleName",
title: "Role",
type: "Custom"
},
{
field: "UserName",
type: "String"
}
],
editable: "popup"
});
grid = $("#grid").data("kendoGrid");
function onAddOpen() {
}
addWindow = $("#add-window");
$(".k-button.k-button-icontext.k-grid-add").click(function () {
if (!addWindow.data("kendoWindow")) {
addWindow.kendoWindow({
title: "Add User",
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: 'myaddurl'
});
}
else {
addWindow.data("kendoWindow").open();
}
addWindow.data("kendoWindow").center();
addWindow.data("kendoWindow").refresh();
return false;
});
});
function onClose() {
$("#refresh-btn").click();
}
function onEditOpen() {
//editWindow.data("kendoWdinow").center();
}
I've hacked Kendo UI for the second time, this time I've solved its incompatibility with jQuery 1.8.3. using the following hack:
$(".k-grid-filter").each(function(index) {
$(this).click(function() {
$($(".k-filter-menu.k-popup.k-group.k-reset")[index]).offset({
left: $($(".k-grid-filter")[index]).offset().left - $($(".k-filter-menu.k-popup.k-group.k-reset")[index]).width(),
top: $($(".k-grid-filter")[index]).offset().top + $($(".k-grid-filter")[index]).height()})
})
});
I've put this hack into the document load event of the page an voila, it works. It surely looks ugly as hell with this hack, but after designing it will look good as new. I'm happy I found a work around, but I'm unhappy I had to hack Kendo UI twice. It is a very nice tool except the bugs.
jQuery 1.8.# is only compatible with Kendo UI - Q2 2012 SP1 (2012.2 913) or later..
If your kendo UI version is earlier, you should update it.
I'm trying to create a very simple bar chart using the results of a JSon action method in MVC. I get the actual bar chart, but I don't understand the options and all that well enough, so I'm basically guessing what to do. I used the example on the HighCharts site as an example for how to get data from server code and create a chart. The difference is my chart is simpler than the example. I don't have categories for each user (as in the fruit example), I only have a user and a number of hours logged.
Here's the HighCharts jQuery code:
function getHighChart() {
var actionUrl = '<%= Url.Action("GetChartData") %>';
var customerId = $('#customersId').val();
var startdate = $('.date-pickStart').val();
var enddate = $('.date-pickEnd').val();
var options = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'bar'
},
title: {
text: 'Statistik'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Timmar'
}
},
series: []
}
jQuery.getJSON(actionUrl,
{ customerId: customerId, startdate: startdate, enddate: enddate }, function (items) {
var series = {
data: []
};
$.each(items, function (itemNo, item) {
series.name = item.Key;
series.data.push(parseFloat(item.Value));
});
options.series.push(series);
var chart = new Highcharts.Chart(options);
});
}
And here's the action method returning JSon:
public JsonResult GetChartData(string customerId, string startdate, string enddate)
{
int intcustomerId = Int32.Parse(customerId);
var emps = from segment in _repository.TimeSegments
where
segment.Date.Date >= DateTime.Parse(startdate) &&
segment.Date.Date <= DateTime.Parse(enddate)
where segment.Customer.Id == intcustomerId
group segment by segment.Employee
into employeeGroup
select new CurrentEmployee
{
Name = employeeGroup.Key.FirstName + " " + employeeGroup.Key.LastName,
CurrentTimeSegments = employeeGroup.ToList(),
CurrentMonthHours = employeeGroup.Sum(ts => ts.Hours)
};
Dictionary<string, double > retVal = new Dictionary<string, double>();
foreach (var currentEmployee in emps)
{
retVal.Add(currentEmployee.Name, currentEmployee.CurrentMonthHours);
}
return Json(retVal.ToArray(), JsonRequestBehavior.AllowGet);
}
I was able to create a pie chart, but now when I want to create a simple bar I'm not able to work out what is what in the jQuery code, so the results I get is a bar where first of all the only user listed in the legend is the last one in the array. Secondly, the tooltip shows x = [The user's name], y = 29, instead of [The user's name]: 29, which I got in the pie chart.
How would I create such a simple bar chart in HighCharts from this JSon?
I use:
//Controller action:
public JsonResult GetData(int id)
{
Dictionary<int, double> data = this.repository.GetData(id);
return Json(data.ToArray(), JsonRequestBehavior.AllowGet);
}
View:
<script>
var chart1;
$(document).ready(function () {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-container-1',
defaultSeriesType: 'scatter',
events: {
load: requestData
}
},
options...
,
series: [{
name: 'some data',
data: []
}]
});
}
);
function requestData() {
$.ajax({
url: '/ControllerName/GetData?id=#(Model.Id)',
success: function (items) {
$.each(items, function (itemNo, item) {
chart1.series[0].addPoint([item.Key,item.Value], false);
});
chart1.redraw();
},
cache: false
});
}
</script>
<div id="chart-container-1"></div>
So basically I use addPoint('array of x,y',false for not redrawing chart)
Well, I worked it out myself after all... I thought I should post it in case some other HighCharts newbie like me is interested:
Here's the jQuery that worked:
function getHighChart() {
var actionUrl = '<%= Url.Action("GetChartData") %>';
var customerId = $('#customersId').val();
var customerName = $('#customersId option:selected').text();
var startdate = $('.date-pickStart').val();
var enddate = $('.date-pickEnd').val();
//define the options
var options = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'column'
},
title: {
text: 'Hours worked for ' + customerName
},
xAxis: {
categories: [customerName]
},
yAxis: {
title: {
text: 'Hours'
}
},
series: []
};
//Calls the JSON action method
jQuery.getJSON(actionUrl,
{ customerId: customerId, startdate: startdate, enddate: enddate }, function (items) {
$.each(items, function (itemNo, item) {
var series = {
data: []
};
series.name = item.Key;
series.data.push(parseFloat(item.Value));
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
}
If someone can find faults in this and point me to a better way to do it, I'll gladly hand over the answer credit, otherwise I'll accept my own answer...