fullcalendar pass in array to set events - ajax

I would like to pass in an array of IDs that will be used to select the events I want to display. The fullcalendar displays all of the events if I do not use the 'data' attribute with the ID array. When the data attribute is added I get the error message 'There was an error fetching events!'
This is the document ready function:
var groupSelectedArray = [];
groupSelectedArray[0] = '1';
groupSelectedArray[1] = '2';
$('#calendar').fullCalendar({
header:
{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
titleFormat: {month: 'MMMM'},
defaultView: 'month',
editable: false,
events: function (start, end, groupSelectedArray, callback) {
$.ajax({
type: "POST",
url: '#Url.Action("GetAllEvents", "Home")',
data: { selectedGroups: groupSelectedArray },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = [];
$(doc).each(function () {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
id: $(this).attr('id'),
description: $(this).attr('description'),
color: $(this).attr('color'),
textColor: 'black'
});
});
callback(events);
} ,
error: function () {
alert("There was an error fetching events!")
}
});
}
This is the C# method:
public JsonResult GetAllEvents(string[] selectedGroups)
{
var eventList = GetEventsFromDatabase(selectedGroups);
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
Can anyone see where I am going wrong?
Thanks.

What I did to get this to work was change the 'data' part of the ajax call:
Replace this:
{ selectedGroups: groupSelectedArray },
to this:
data: JSON.stringify(groupData),

Related

How can I recieve multiple arrays in ajax, passed as JSON from the controller method in laravel?

I'm trying to pass multiple arrays using JSON response from the controller method in laravel but I wanted to know how to fetch them in an ajax call. I'm a beginner so please correct if I'm wrong.
I'm already fetching events from calendar using ajax but now i want to fetch tasks as well.
Controller method:
$events = Event::all();
$tasks = Task::all();
return response()->json([
'events' => $events,
'tasks' => $tasks
]);
Ajax:
var events = [];
var tasks = []; //step 2
$.ajax({
url:'events',
type: "GET",
datatype: 'json',
cache: false,
success: function(data){
alert(data);
$.each($.parseJSON(data), function(index, val){
//alert(data);
events.push({
id: val.id,
title: val.name,
start: val.start_date,
end: val.end_date,
start_time: val.start_time,
end_time: val.end_time,
location:val.location,
description: val.description,
calendar_type: val.calendar_type,
timezone: val.timezone,
allDay: val.isFullDay
});
})
//$this.$calendarObj.fullCalendar('renderEvents', events);
generateCalendar(events);
},
error : function(error){
console.log(error);
}
});
var events = [];
var tasks = []; //step 2
$.ajax({
url:'events',
type: "GET",
cache: false,
success: function(data){
alert(data);
$.each(data.events, function(index, val){
//alert(data);
events.push({
id: val.id,
title: val.name,
start: val.start_date,
end: val.end_date,
start_time: val.start_time,
end_time: val.end_time,
location:val.location,
description: val.description,
calendar_type: val.calendar_type,
timezone: val.timezone,
allDay: val.isFullDay
});
})
//$this.$calendarObj.fullCalendar('renderEvents', events);
generateCalendar(events);
},
error : function(error){
console.log(error);
}
});

Change Kendo Grid Cell With Ajax Response When Another Cell Changes

Using a Kendo grid with 3 columns, I have an event that fires when the first column is changed that makes an ajax call and returns some data. I want to update the second column with the returned data but I'm not having any luck and I'm not even sure if this is the correct approach. I can change the second column with static data by adding a change event to my datasource of my grid, but that of course doesn't help. The only examples I can seem to find show changing another column with client side data, not data returned from the server. Here's what I have so far:
$("#manualStatsGrid").kendoGrid({
dataSource: this.GetManualStatisticsDataSource(),
sortable: true,
pageable: false,
filterable: true,
toolbar: ["create"],
editable: "inline",
messages: {
commands: {
create: "Add New Statistic"
}
},
edit: function (e) {
var _this = _manualStats;
var input = e.container.find(".k-input");
var value = input.val();
input.keyup(function(){
value = input.val();
});
$("[name='Statistic']", e.container).blur(function(){
var input = $(this);
$("#log").html(input.attr('name') + " blurred " + value);
//valid the GL account number
$.ajax({
type: "GET",
url: _this.ValidateGlUrl,
dataType: 'json',
data: { glNumber: value },
success: function (response) {
var newDescription = response.Data.description;
console.log(newDescription);
//change description column here?
},
error: function (response) {
console.log(response);
}
});
});
},
columns: [
{ field: "Statistic" },
{ field: "Description" },
{ field: "Instructions" },
{ command: ["edit", "destroy"], title: " ", width: "250px"}
]
});
}
this.GetManualStatisticsDataSource = function () {
var _this = _manualStats;
var dataSource = {
type: "json",
transport: {
read: {
type: "POST",
url: _this.GetManualStatisticsUrl,
dataType: "json"
},
update: {
type: "POST",
url: _this.UpdateManualStatisticsUrl,
dataType: "json"
},
create: {
type: "POST",
url: _this.CreateManualStatisticsUrl,
dataType: "json"
},
destroy: {
type: "POST",
url: _this.DeleteManualStatisticsUrl,
dataType: "json"
}
},
schema: {
model: {
id: "Statistic",
fields: {
Statistic: {
type: "string",
editable: true,
validation: { required: true, pattern: "[0-9]{5}.[0-9]{3}", validationmessage: "Please use the following format: #####.###" }
},
Description: { editable: false },
Instructions: { type: "string", editable: true }
}
}
}
Inside the edit event, you have e.model. The model has the method set() which can change any dataItem's property value:
edit: function (e) {
...
var editEvent = e; // Creates a local var with the edit's event 'e' variable to be available inside the 'blur' event
$("[name='Statistic']", e.container).blur(function() {
...
$.ajax({
...
success: function(e, response) { // 'e' inside this callback is the 'editEvent' variable
e.model.set("Description", response.Data.description); // e.model.set() will change any model's property you want
}.bind(null, editEvent) // Binds the 'editEvent' variable to the success param
});
});
Working demo
Made this snippet of top of my head. Tell me if there is something wrong with it.

jQuery ui autocomplte in jQGrid popup position issue

I have following code in jQgrid and I am using jQuery ui autocomplete in one of the field. But the pop up of autocomplete displays somewhere else as shown in figure. From IE developer tools I noticed the results are attached to body tag, which is at the end of the page. I tried using appendTo, but that doesn't help.
{
name: 'nameAccount',
index: 'nameAccount',
width: 300,
editable: true, sortable: false, resizable: false,
shrinkToFit: true
,editoptions: {
dataInit: function (elem) {
var autocompleteSource = function(request, response,term) {
var param = request.term;
$.ajax({
url: myUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (myyydata) {
//alert('HI-Success');
//response( myyydata );
response($.map(myyydata, function (item) {
return {
label: item.AccountInfo,
value: item.AccountInfo
}
}));
} ,
error: function (res, status) {
alert('HI-error');
//alert(res.status+" : "+res.statusText+". Status: "+status);
}
});//END AJAX
};
$(elem).autocomplete({
source: autocompleteSource,
//appendTo: "#"+elem.id,
position: { collision: "flip" },
minLength: 2
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
minnu4515. i guess it is because of the css misalignment. i faced the similar problem and i manually set the z-index alignmnet. that solved my issue.
$('.ui-autocomplete').css('zIndex',1000);

How can I load all events on calendar using Ajax?

I want to load all events on FullCalendar using AJAX when I clicked next-previous-button in agenda-views.
I guess, when will click on next-previous-button then I'll send current date('y-m-d') to url: 'fetch-events.php' then it will return event{ id: ,title: , start: , end: , allDay: } format data for rendering on calendar
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: false,
selectHelper: false,
editable: false,
events: // on-click next-previous button load events using Ajax
// post date using Ajax, then query to fetch all events and return data
});
JSON not working in my case
From the FullCalendar Online Documentation
FullCalendar will call this function whenever it needs new event data.
This is triggered when the user clicks prev/next or switches views.
This function will be given start and end parameters, which are
Moments denoting the range the calendar needs events for.
timezone is a string/boolean describing the calendar's current
timezone. It is the exact value of the timezone option.
It will also be given callback, a function that must be called when
the custom event function has generated its events. It is the event
function's responsibility to make sure callback is being called with
an array of Event Objects.
Here is an example showing how to use an event function to fetch
events from a hypothetical XML feed:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: 'myxmlfeed.php',
dataType: 'xml',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
Source
I made some little changes:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
jQuery.ajax({
url: 'schedule.php/load',
type: 'POST',
dataType: 'json',
data: {
start: start.format(),
end: end.format()
},
success: function(doc) {
var events = [];
if(!!doc.result){
$.map( doc.result, function( r ) {
events.push({
id: r.id,
title: r.title,
start: r.date_start,
end: r.date_end
});
});
}
callback(events);
}
});
}
});
Notes: start and end MUST be ISO 8601. Another change was the use of format instead of unix (this made easier for me to deal with the code-behind)
There is a built in option avaliable
var calendar = new FullCalendar.Calendar(calendarEl, {
events: '/myfeed.php'
})
more details https://fullcalendar.io/docs/events-json-feed
This is perfect way to load data properly.
// if you want to empty events already in calendar.
$('#calendar').fullCalendar('destroy');
$.ajax({
url: 'ABC.com/Calendar/GetAllCalendar/',
type: 'POST',
async: false,
data: { Id: 1 },
success: function (data) {
obj = JSON.stringify(data);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
//isRTL: true,
buttonHtml: {
prev: '<i class="ace-icon fa fa-chevron-left"></i>',
next: '<i class="ace-icon fa fa-chevron-right"></i>'
},
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
//obj that we get json result from ajax
events: JSON.parse(obj)
,
editable: true,
selectable: true
});
fullCalendar already uses ajax, so you don't have to type it. When I was starting to implement fullCalendar I used the solution of the most voted answer here:
https://stackoverflow.com/a/25404081/3927450
but then I could prove, that fullCalendar is in charge of making the ajax call the times the view changes without you having to do anything. I find this plugin very useful, although the documentation did not seem very clear to me.
So this code:
events: function(start, end, timezone, callback) {
jQuery.ajax({
url: 'schedule.php/load',
type: 'POST',
dataType: 'json',
is exactly this:
events: schedule.php/load,
you only have to provide the url. Off course you have to deal with a proper JSON response from the server. Or if you need more params you can do it like this:
events: {
url: '/myfeed.php',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
var events= '';
$.ajax({
url: '/eventoscalendar',
dataType: 'json',
type: 'GET',
success: function(data) {
events= JSON.stringify(data);
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
displayEventTime: true,
selectable: true,
droppable: false,
events: JSON.parse(events)
});
}
});
y en /eventoscalendar
public function eventoscalendar()
{
$events[]= [
"title" =>'Meeting',
"start"=> date('Y-m-d'),
"allDay"=> false,
"url"=> 'http://google.com/'
];
return JsonResponse::create($events, 200, array('Content-Type'=>'application/json; charset=utf-8' ));
}

Load data into Highcharts with Ajax

I am trying to update high charts on page load and on select menu change with JQUERY AJAX call. There is data being returned in [[10,1228800000],[10,1228800000]] format.The chart is blank and does not graph any of the data.
Tried several solutions posted on here but none worked.
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'stats',
defaultSeriesType: 'spline'
},
title: {text:''},
xAxis: {
type: 'datetime'
},
yAxis: {},
series: []
};
var month = 'July';
$.ajax({
type: "POST",
data: "month="+month,
url: "update_visits_chart",
success: function (data) {
options.series.push(data);
chart = new Highcharts.Chart(options);
}
});
Any errors? thanks in advance.
EDIT:
MOST RECENT CODE STILL NOT WORKING:
var options = {
chart: {
renderTo: 'stats',
type: 'spline'
},
title: {
text: ''
},
xAxis: {
type:'datetime',
tickInterval: 30 * 24 * 3600 * 1000,
dateTimeLabelFormats: {
day: '%b %e'
},
labels: {
rotation: -45,
align: 'right'
}
},
yAxis: {
title: {
text: 'Number of visits'
},
min: 0
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%b %e', this.x) +'<br />'+this.y+' visit(s)';
}
},
legend: {
enabled: true
},
credits: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Number of Visits',
data: []
}]
};
var month = 'July';
$.ajax({
type: "POST",
url: "update_visits_chart",
data: "month="+month,
success: function(data){
options.series[0].data = data;
chart = new Highcharts.Chart(options);
}
});
You have to use the setData methode of the series object as descriped in documentation. In your case it is options.series[0].setData(Data)
And I think you have to turn your Ajax result from string to a real object/array by using JSON.parse(data).
EDIT:
#Ricardo Lohmann: in the ajax-call he did not specify the dataType he expects in the response, so jQuery will guess the dataType. But it will not recognize a string starting with [ as JSON and I doubt his response will be served with correct mime type application/json. So specifying the correct mime type should also solve the problem. But I do not have an example of the complete ajax respons of the questioner. So I'm just guessing, too.
I'd recommend the following ajax call:
$.ajax({
type: "POST",
url: "update_visits_chart",
data: {month: month},
dataType: 'json',
success: function(data){
options.series[0].setData(data);
}
});
#Jugal Thakkar
$.getJSON is just a shortcut for the ajax-call above, but it is less flexible because you have less options.
You have to set directly data to series because data is already a multidimensional array.
The following code will fix it.
Change options.series.push(data); to options.series = data;

Resources