Using AJAX response to fill JSON object - javascript

I'm using fullcalender.io which takes in a json array of objects. I'm using AJAX to call a php function, which succesfully returns a JSON object which i can see in the console. I just can't get it to full up the events object as it tells me events is not defined. I've tried initiating var events before but it doesnt the variable isnt defined.
$('#calendar').fullCalendar({
events: [
//Here needs to be filled
],
dayClick: function(date, jsEvent, view) {
var data = {
action: 'getCountOfReservationOnDate',
date: date.format() + " 00:00:00"
}
$.ajax({
type: 'POST',
url: "/modules/ajax/ajax_handler.php",
data: data
})
.done((result)=>{
if(result) {
console.log(data);
console.log(JSON.parse(result));
events.push(result); //From here
} else {
alert("Failed.")
console.log(result);
}
})
.fail(function($xhr) {
var data = $xhr.responseJSON;
//$("#validationError").text(data.message);
console.log(data.message);
})
.always(()=>{
//$('#loader').hide();
})
}

fullcalender.io provide some documentation related to ajax usage (events as a json feed). Consider the following script:
var calendar = new Calendar(calendarEl, {
events: '/modules/ajax/ajax_handler.php'
});
You might need to change your /modules/ajax/ajax_handler.php to provide the correct output. Since you did not post the code from it I'm not able to check it, but you probably find the answer on the linked document.

Your can try creating a variable where your ajax function can access it,
or create that variable globally at the topmost line in your file
tempEvent
$('#calendar').fullCalendar({
events: [
//Your can for loop the tempEvent to fill here
],
dayClick: function(date, jsEvent, view) {
var tempEvent = []
var data = {
action: 'getCountOfReservationOnDate',
date: date.format() + " 00:00:00"
}
$.ajax({
type: 'POST',
url: "/modules/ajax/ajax_handler.php",
data: data
})
.done((result)=>{
if(result) {
console.log(data);
console.log(JSON.parse(result));
tempEvent.push(result); //From here
} else {
alert("Failed.")
console.log(result);
}
})
.fail(function($xhr) {
var data = $xhr.responseJSON;
//$("#validationError").text(data.message);
console.log(data.message);
})
.always(()=>{
//$('#loader').hide();
})
}

Related

can i put schedule in fullcalendar as ajax?

I want to add the ability to schedule in fullcalendar, Laravel. The method is working as expected however, I do not understand what to do with the response data.
$('#calendar').fullCalendar({
header: {
left : 'today, prev,next',
center: 'title',
right : '',
},
locale:'ko',
height:'parent',
events : function(start, end, timezone, callback){
var month = $('#calendar').fullCalendar('getDate').format('YYYY-MM');
var url = '{{route('reservation.get_schedule',[request()->id])}}';
alert(url)
$.ajax({
type : 'get',
data : {'date' : month},
url : url,
datatype : 'json',
success : function(data){
console.log(data); // How do I use the data
}
});
}
});
The documentation for events-as-a-function says:
[The function]... 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.
There's also an example on that page where the callback function is employed to pass the event data returned from the AJAX call into fullCalendar.
So in your case (assuming that your event data is already in the format required by fullCalendar and doesn't need any transformation) you would simply add a call to this function inside your "success" callback:
events : function(start, end, timezone, callback){
var month = $('#calendar').fullCalendar('getDate').format('YYYY-MM');
var url = '{{route('reservation.get_schedule',[request()->id])}}';
alert(url)
$.ajax({
type : 'get',
data : {'date' : month},
url : url,
datatype : 'json',
success : function(data){
console.log(data);
callback(data); //pass the event data to fullCalendar via the provided callback function
}
});
}
$('#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);
}
});
}
});
DOC

unable to create dynamic events in fullcalendar

i have a situation in which i m trying to create events dynamically using the plugin fullcalendar im trying to create events with the help of the ajax call and the data retrieved is in the form of json
when i m trying to create events only event at index 0 is getting created rest of events are not created
the javascript code is as follows
function showData()
{
var ids = showValidData();
if (ids.length != 0)
{
$.ajax({
url: $("#base-url").val() ,
type: 'POST',
data: {'ids': ids},
dataType: 'json',
success: function (response)
{
var data = response.data;
var myevents = [];
if (response.success)
{
$(data).each(function (index, value) {
myevents.push({
title: value.layoutName,
start: value.startDate,
end: value.endDate
});
});
console.log(myevents);
$(".fc-event-container").click();
$('#calendar-example-1').fullCalendar({
events: myevents,});
return;
}
}
});
}
}
Set events when initializing FullCalendar - define the url of the script that returns a json of events from your database (https://fullcalendar.io/docs/event_data/events_function/). If you want to dynamically refresh the calendar , you can add a setInterval ontop:
$(document).ready(function(){
setInterval(function(){$('#calendar').fullCalendar('refetchEvents')}, 30000);
$("#calendar").fullCalendar({
...
events: {
url: 'script.php',
type: 'POST',
data: {
data1: x,
data2: y
},
success : function(response){
// do something
},
}
});
});

Issue in displaying events in Fullcalendar.js

Hi I am trying to implement FullCalendar.js with Asp.Net MVC. I am abl to show empty calendar but my events are not getting loaded in the Calendar.
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",
success: function (doc) {
debugger;
$('#calendar').fullCalendar();
var events = [];
$(doc).find('[object Object],[object Object]').each(function () {
debugger;
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
// });
$('#calendar').fullCalendar('refetchEvents');
// callback(events);
}
});
it comes to success method and it has two events in it . but dont know why theseevents are not loaded into FullCalendar and also after this Calendar is not comingg automatically.
I guess it is not going in events.push. When I do hover on doc it shows "[object Object],[object Object]" and in this it has two records on [0] and [1].
Please help me in this.
Try using
$('#calendar').fullCalendar( 'rerenderEvents' )
after your events have been pulled.
Also, make sure to use the code from the official documentation properly. Try the following (untested):
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",,
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);
}
});
}
});
If you now want to refetch your events, call :
$('#calendar').fullCalendar('refetchEvents');
where necessary.
EDIT:
Since your are actually pulling data from a JSON feed, the following code may even be enough:
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary'
});
Check the documentation here:
EDIT2:
To dynamically modify the request you send to the backend (depending on a dropdown or something else), may be achieved as follows:
var myValue = 10;
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary',
data: function() { // a function that returns an object
return {
dynamic_value: myValue
};
}
});

How to reset the data after init , Select2

I use Select2-4.0.0 I have been struggling with this problem for a whole day that to update the data.
I search every posts I can like Update select2 data without rebuilding the control, but none have them work.
What I need is really simple (a setter to data):
I have a diaglog, which had a select. Every time I open the diaglog, I will ajax for an data to keep it in a local array like:
when dialog open :
var select2List=syncToLoadTheData();//data for select2
$('#search-user-select').select2({ //here when secondly executed, the select2's data on UI does not refreshed
data:select2List,
matcher: function(params, data){
var key = params.term;
if ($.trim(key) === '') {
return data;
}
if( (matchKeyAndPinyin(key,data.text))){
return data;
}
return null;
}
}
But the problem is even though the list is changing, the select options does not change at all.Please note in my test case, every time i open the dialog, the data from server is changed:
What I had tried:
1.when init:
data: function() { return {results: select2List}; }// not work to show any data at all
2.when secondly open dialog:
$( "#search-user-select").select2('data',newdata,true);//not work to have the new data
3.when secondly open:
$("#search-user-select").select2("updateResults");//Error, does not have this method
And some other method like directly change the array's data(only one copy of the data), but none of them work.
I had the same problem before, my problem was i need to update the select2 after every ajax request with new data.
and this how i fixed my code.
EventId = $(this).attr('id');
$.ajax({
url: 'AjaxGetAllEventPerons',
type: 'POST',
dataType: 'json',
data: {id: EventId},
})
.done(function(data) {
$("#select2_job").select2({
minimumInputLength: 2,
multiple:true,
initSelection : function (element, callback) {
//var data = data;
callback(data);
},
ajax: {
url: "/AjaxGetAllPersonForEvent",
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.fullname
});
});
return {
results: myResults
};
}
}
});
I hope this example will help you to solve your problem

fullcalendar js: fetching more events with ajax

I'm using fullcalendar,
how can I fetch more events from same server side, multiple urls?
The initial one works, I just want to add additional events when they arrive(ajax).
You could use Ajax to get the data and then add dynamically the new source
$.ajax({
url: "test.html",
success: function(data){
var source = { events: [
{
title: data.getTitle(),
start: new Date(year, month, day)
}
]};
$('#calendar').fullCalendar( 'addEventSource', source );
}
});
If each and every time you are using a different URL, then you can simply use addEventSource with the new URL.
If you are attempting to use the same URL, you can get all events (old and new) using refetchEvents.
You can also get the JSON and create the event as a client event using renderEvent. The latter is the most "ajax-y" of the options. In this case have your source return the JSON that represents the events, iterate through the array of new events, and call renderEvent on it.
// this call goes in a poll or happens when the something should trigger a
// fetching of new events
$.ajax({
url: "path/to/event/source",
success: function(data){
$.each(data, function(index, event)
$('#calendar').fullCalendar('renderEvent', event);
);
}
});
The ajax call done can also insert in the calendar code
$.ajax({
url: url,
type: 'GET',
data: { },
error: function() {
alert('there was an error while fetching events!');
}
}).done(function (doc) {
var event = Array();
$.each(doc, function(i, entry)
event.push({title: entry.title, start: entry.start});
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2014-06-12',
editable: true,
events: event
});
});

Categories