FullCalendar: Using JSON feed containing a dynamic quantity of event sources - javascript

I have a case where I need to display multiple eventSources on a calendar, but don't know the quantity of sources until runtime. I've created a javascript function with an AJAX call to a PHP script to create a valid JSON feed (verified with an online tool), and am trying to drop that JSON data into the initialization of the calendar. I've tried it with FullCalendar 1.6.4 and 2.0.0 and it doesn't display any events or throw any errors. The odd part is I can copy the stringified version of the JSON feed into the eventSources and it works. Any ideas?
Here's the stringified JSON data:
[
{
"url": "/s/events.php?e=7",
"type": "GET",
"color": "#ffcc00",
"textColor": "#000000"
},
{
"url": "/s/events.php?e=59",
"type": "GET",
"color": "#ff6600",
"textColor": "#ffffff"
}
]
Heres the FullCalendar initialization code with the JSON data (dataSources not stringified):
function loadCal(dataSources) {
$('#calendar').fullCalendar({
eventSources: [
dataSources // Here's the JSON data
],
editable: true,
...
}
I've tried using the stringified version of dataSources and that results in an unusable URL (e.g., test.com/[%7B%22url%22:%20%22/s/events.php?e=7%22,%22type%22:%20%22GET%22,%22color%22:%20%22).
I'm open to suggestions of alternate approaches. Thanks.
Here's the code as I updated following the suggestion by Bhutto:
function loadCal() {
$('#calendar').fullCalendar({
eventSources: [
function() {
var userData = $.ajax( {
url: '/s/calendar_userdata.php',
method: 'GET',
dataType: 'json',
success: function(userData) {
//console.log(userData);
var user_count = userData.length;
var source = [];
var jsonData = [];
// Create the sources
for (var i = 0; i < user_count; i++)
{
var uid = userData[i].uid;
if(!source[i]) source[i] = [];
source[i] = '/s/events.php?e=' + uid;
// Add each source to a JSON feed object
jsonData.push({
url: source[i],
type: 'GET',
color: userData[i].cal_color,
textColor: userData[i].txt_color,
error: function() { alert('There was an error loading calendar data.');}
});
}
console.log(jsonData); // In the console I can see well formed JSON data
return jsonData;
}
});
}
],
editable: true,

Related

FullCalendar not displaying events on the calendar interface

FullCalendar is not displaying the events on the interface even though the format for (events) as a json feed is correct. Below is an example of the array from which I feed in the events to the calendar. I am also able to get the data on the console, indicating that the api is returning with the events correctly, it is just not populating on the interface. What can be causing this issue?
[
{
"title": "Football game",
"start": "2021-06-08T06:00:00",
"end": "2021-06-08T07:00:00"
},
{
"title": "Catch up call",
"start": "2021-06-09T00:00:00",
"end": "2021-06-09T02:00:00"
}
]
Below is the code where i am initiating and rendering the calendar
let $calendar = $('.calendar-display')
var calendarEl = document.getElementById('calendar');
let calendar = new Calendar(calendarEl, {
plugins: [dayGridPlugin,timeGridPlugin],
events: "../apis/calendar",
initialView: "timeGridWeek",
allDaySlot: false,
slotEventOverlap: false
});
var start = "6/6/2021"
var end = "6/13/2021"
retrieveData(start,end)
function retrieveData(start, end) {
let configData = {start: start, end: end};
console.log(configData)
$.ajax({
method: 'GET',
url: "../apis/calendar",
contentType: 'application/json',
dataType: 'json',
data: configData,
success: function (data) {
console.log(data)
calendar.render()
},
error: function (error) {
console.log("error here",error);
}
})
};
});
calendar.render()
}
The response in console
Api call in network tools
It returns a null array for the fullCalendar ajax request, even though it is pointing to the same endpoint

how to make redraw datatables after ajax response

I have a problem here, first I create data tables after I select the user using select2, so the data is dynamic according to the selected user, then next to it there is an update data button, here serves to update the data from the API if there is the latest data, for the process the data update is no problem, but there is a problem in the data tables process where after the update process, the data tables don't want to be redrawn
$("#name").on("change",function(){
var cek_id = this.value;
$("#user_id").val(cek_id);
console.log(cek_id);
$('#getData').DataTable().clear().destroy();
var i = 1;
var VendorClient = $("#getData").DataTable({
order: [ 0, "asc" ],
processing: true,
serverSide: false,
ajax: "{{route('get-user-data')}}"+"/"+cek_id,
columns: [{
data: null,
render: function ( data, type, full, meta ) {
return meta.row+1;
} },
{
data: "fullname",
name: "fullname",
orderable:false
},
{
data: "date",
name: "date",
orderable:false
}
]
});
});
and here is the process when the data update is clicked
$("#get_data").on("click",function(){
var cek_id = $("#user_id").val();
var url = "{{route('get-update-data')}}"+"/"+cek_id,
$.ajax({
type: "get",
url: url,
dataType: "json",
success:function(data){
if(data.status=='success'){
$('#getData').data.reload();
}else{
$('#getData').data.reload();
}
}
});
});
I have tried various methods, including creating a globe variable for VendorClient, then after response ajax i'm adding this code VendorClient.ajax.reload(null, false); and get errorr (index):406 Uncaught (in promise) TypeError: Cannot read property 'ajax' of undefined
but it's not working, any ideas?
Try to redraw the table:
$('#getData').DataTable().clear().draw();
or
$('#getData').DataTable().columns.adjust().draw();
or
$('#getData').DataTable().columns.adjust().draw(false);

Convert data from received JSON format to JVectorMap format

I am developing dashboard of a MIS in MVC 5, and in that dashboard I want to use JVectorMap to load the registered countries. So following is my controller action that returns the JSON
public JsonResult registeredCountries()
{
var ret = db.View_RegisteredCountries.Select(x => new { Key = x.CountryCode, Value = x.TotalCompanies }).ToDictionary(x => x.Key, x => x.Value).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
and following is my JS code to get the JSON
var data = {};
$.ajax({
url: 'registeredCountries',
type: 'GET',
traditional: true,
async: false,
cache: false,
//async: false,
dataType: 'json'
}).done(function(result) {
data = result;
});
But my problem is that JVectorMap use the array in the following format
data_array = {
"US": 4977,
"AU": 4873,
"IN": 3671,
"BR": 2476,
"TR": 1476,
"CN": 146,
"CA": 134,
"BD": 100
};
but the returned JSON is in the following format
[{ "Key": "SA", "Value": 4 }]
How do I convert the above JSON to the following format so that JVectorMap could be populated.
data_array = {
"SA":4
}
Simply a matter of walking the array of inputs and create an object from each entry.
// set up some sample data - in your case you already have this.
var data = JSON.parse('[{"Key":"SA","Value":4},{"Key":"US","Value":12},{"Key":"BR","Value":6}]')
var obj={} // make a new object to build results.
for (var i =0; i < data.length; i = i + 1) {
obj[data[i].Key] = data[i].Value
}
// Note jquery only used for this debug output.
$("#output").html(JSON.stringify(obj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>

Get JSON data with AJAX and then modify raphael.js script

This is what I want to achieve:
I want to create an interactive map using raphael.js.
Using Php, I get datas from MySql DB and converted into a JSON file.
So far so good.
Inside my raphael js file, I must now:
get those datas
use them in order to modify my raphael file.
I am currently stuck at this first step.
Here's my simplified JSON file (let's call it countries.json) :
[
{
"id": "1",
"type": "Country",
"title": "France",
"published": "1",
"description": "Republic"
},
{
"id": "2",
"type": "Country",
"title": "Belgium",
"published": "0",
"description": "Monarchy"
}
]
Here comes the simplified raphael.js
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': '', 'title': '', 'description':''});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': '', 'title': '', 'description':''});
countries.push(france,belgium);
At the end of the raphael js, I make an Ajax request (using jquery) to get my JSON datas :
$.ajax({
type : 'GET',
url : 'system/modules/countries.json',
data: {get_param: 'value'},
dataType : 'json',
success : function(data, statut){
console.log(statut);
},
error : function(data, statut,erreur){
console.log(statut);
},
complete: function (data) {
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
}
});
Here come the troubles:
I get a 'success' status trough the success function.
BUT I got an error while completing the script :
Uncaught SyntaxError: Unexpected token o
What did I miss? Can't figure out what is different from http://jsfiddle.net/fyxZt/4/ (see how to parse json data with jquery / javascript?)
That was just for part 1 :-)
Assuming someone could help me to fix that, I still then have no idea how to write js loop that will set the raphael vars attributes as it:
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': 'Country', 'title': 'France', 'description':'Country'});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': 'Country', 'title': 'Belgium', 'description':'Monarchy'});
communes.push(france,belgium);
Thanks an advance for your help and please excuse my unperfect english!
Vinny
There is no data argument passed to the complete callback,
according to jQuery API:
complete
Type: Function( jqXHR jqXHR, String textStatus )
(...)The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").
So you only need to use the success callback :
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
var json = data;
$(json)
.each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
});
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
Concerning your second question, you cannot interact directly with variable name (accessing dynamic variable) in js, so you'll need to create an object where values are indexed by one of your json's values. However, the cleanest way to handle this would probably be to add your paths to the json...
var rsr = Raphael('map', '548', '852');
var countries = [];
//here I used the "id" property from the json
var paths={
"1":rsr.path("M ... z"),
"2":rsr.path("M ... z")
};
countries.push(france,belgium);
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
datas.forEach(function (country) {
paths[country.id].data(country);
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});

Format JSON from controller for use by a plugin

I'm getting a JSON string from my controller:
public ActionResult Highlight()
{
var statesHighlight =
db.Jobs
.Select(r => r.Location);
return Json(statesHighlight , JsonRequestBehavior.AllowGet);
}
I'm getting it via an Ajax request like so:
$.ajax({
async: false,
url: '#Url.Action("Highlight", "Jobs1")',
data: JSON.stringify(),
type: 'POST',
success: function (data) {
citydata = data;
}
});
The issue is that this doesn't maintain the format of my string. Calling the controller action shows that it's correctly formatted JSON, but once it comes out of my Ajax request, it's not. Here it is directly from the controller:
["HDQ","HDQ","EVA","HDQ","HDQ","HDQ","EVA","SVF","SVF","SVF","SVF","DFC","DCF","Feedlot","DCF","DCF","DCC","AGNW","AGNW"]
Is there any way that I can ensure that this is the value set to the variable before I pass it along to my plugin?
The plugin I'm using is called ImageMapster. Currently, I have the JSON hard coded for it and it works as intended.
var data = $.parseJSON($('#map-data').text());
var cities = $.parseJSON($('#city-data').text());
$('img').mapster({
mapKey: 'state',
clickNavigate: true,
isSelectable: false,
highlight: false,
onConfigured: function () {
// make the array into a comma-sparated list
var state_list = data.join(',');
var city_list = cities.join(',');
// the 'set' activates the areas
$('img').mapster('set', true, state_list, options = { fillColor: '638EA5' });
$('img').mapster('set', true, city_list, options = { fillColor: 'ffffff' });
}
});
Is your statesHighlight just a simple System.String[] ? then you will get always the plain string array object in your javascript.
But you want something like var a = { data1 : "a", data2 : "b", data3 : "c" };
JSON basically consists of Key & Value. The equivalent of the data type in C# would be Dictionary. You need to pass Dictionary type or any other key&value object when you parse your data to Json.
public ActionResult Highlight()
{
var statesHighlight =
db.Jobs
.Select(r => r.Location);
// statesHighlight should be Dictionary
// if you want a JSON result having keys and values.
return Json(statesHighlight , JsonRequestBehavior.AllowGet);
}
In case you need just a keyname for the string array, you can set up a keyname like this.
//return Json(statesHighlight , JsonRequestBehavior.AllowGet);
return Json(
new {
keyname = statesHighlight
}
, JsonRequestBehavior.AllowGet
);
I was looking the wrong place entirely for an answer. The formatting was just fine; I discovered this when I took a closer look at the formatting of the variables I was originally using. As it turns out, I was making things more complicated than they needed to be. Bypassing one of my incremental steps ended up being the right solution. Here is my final code:
//retrieve JSON strings from controller
var citydata = {};
$.ajax({
async: false,
url: '#Url.Action("Highlight", "Jobs1")',
method: 'GET',
success: function (data) {
citydata = data;
}
});
var statedata = {};
$.ajax({
async: false,
url: '#Url.Action("HighlightState", "Jobs1")',
method: 'GET',
success: function (data) {
statedata = data;
}
});
//imagemapster to generate map behaviors
$('img').mapster({
mapKey: 'state',
clickNavigate: true,
isSelectable: false,
highlight: false,
onConfigured: function () {
// make the array into a comma-sparated list
var state_list = statedata.join(',');
var city_list = citydata.join(',');
// the 'set' activates the areas
$('img').mapster('set', true, state_list, options = { fillColor: '638EA5' });
$('img').mapster('set', true, city_list, options = { fillColor: 'ffffff' });
}
});

Categories

Resources