JSON + Array events in same calendar? - json

Good afternoon, currently using JSON feed for my calendar which works ok. Is it possible for me to also add a few events via an array and change colour of these? I want to add bank holidays as an array and colour them green where possible?
Currently my code looks loike this, could I add array of events under the json feed?
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
startParam: 'start',
endParam: 'end',
editable: true,
minTime: 9,
maxTime: 21,
allDayDefault: false,
events : {
url: 'json-events.php',
}
});
Any advice appreciated..

Try this:
In document.ready() method or just before your calendar code. Create event sources like this:
source1 = {
url: 'json-events.php',
type: 'POST',
error: function() {
//alert('There was an error while fetching events!');
},
color: '#4ca64c',
textColor: 'black'
};
source2 = {
url: 'array-events.php',
type: 'POST',
error: function() {
//alert('There was an error while fetching events!');
},
color: '#4caca4',
textColor: 'black'
};
The in fullCalendar declaration:
$('#calendar').fullCalendar({
...
eventSources: [
// your event source
source1,
source2
],
...
});
Hope this helps

Related

Using Laravel API Resource to get events in fullcalendar

I'm trying to use Laravel API + Vue to render events in FullCalendar.
In Vue I have the code:
<FullCalendar
ref="fullCalendar"
class="calendar"
default-view="dayGridMonth"
:header="{
left: 'title',
center: '',
right: 'prev,next today',
}"
:plugins="calendarPlugins"
:weekends="calendarWeekends"
:events="calendarEvents"
locale="it"
:firstDay="1"
#dateClick="handleDateClick"
#eventClick="handleEventEdit"
/>
...
components: {
FullCalendar,
},
data: function() {
return {
calendarPlugins: [
dayGridPlugin,
interactionPlugin,
],
editable: true,
calendarWeekends: true,
calendarEvents: this.elist,
eventFormVisible: false,
elist: [],
};
},
...
created() {
this.getElist();
},
methods: {
async getElist() {
this.Equery.user_id = this.userId;
this.elist = await eventResource.list(this.Equery); // http://mysite.test/api/events?user_id=1
this.elist = this.elist.data;
},
...
API response seems correct:
{"data":[{"id":2,"user_id":1,"job_id":null,"job":"2018-090-01","title":"2018-090-01 : 2","hours":2,"start":"2019-11-06T00:00:00+0000","end":"2019-11-06T00:00:00+0000"},{"id":3,"user_id":1,"job_id":null,"job":"2018-090-01","title":"2018-090-01 : 1","hours":1,"start":"2019-11-29T00:00:00+0000","end":"2019-11-29T00:00:00+0000"}]}
but events are not loaded
For debug purpose I try with:
calendarEvents: 'https://fullcalendar.io/demo-events.json'
and it works!
I can't find the error, I need help.
Thanks in advance.

JQgrid - cannot get output from Json where value of array is Object, Object

I have 2 applications that use the free version of jqgrid.
The one that works has a Json array as follows;
Notice the value of data is [...]
For the application where the data does not get rendered;
Notice the value of data is NOT [...]. So what do I need to do to the data to get it in the correct format so that it will render?
EDIT
I think the data issue I raised originally was mistaken.
I have a jsFiddle of what I want and it works, see
https://jsfiddle.net/arame/cxh7zh3a/
But my code in my .Net MVC application does not. The grid is displayed with headers, but the data rows are not rendered.
var populateGrid = function (data) {
var grid = $("#grid");
grid.jqGrid({
data: data,
colNames: ["Contract No", "Title", ""],
colModel: [
{ name: "FullContractNo", label: "FullContractNo", width: 80, align: "center" },
{ name: "ContractTitle", label: "ContractTitle", width: 400, searchoptions: { sopt: ["cn"] } },
{ name: "Link", label: "Link", search: false, align: "center" }
],
cmTemplate: { width: 100, autoResizable: true },
rowNum: 20,
pager: "#pager",
shrinkToFit: false,
rownumbers: true,
sortname: "FullContractNo",
viewrecords: true
});
grid.jqGrid("filterToolbar", {
beforeSearch: function () {
return false; // allow filtering
}
}).jqGrid("gridResize");
$("#divLoading").hide();
}
var getGrid = function () {
var url = GetHiddenField("sir-get-selected-contract-list");
var callback = populateGrid;
dataService.getList(url, callback);
}
getGrid();
The code is a little different to the JsFiddle as the data is extracted from a Web API.
The data is correct however, as I put a breakpoint in and check it.
See
I have found the answer! I feel daft posting this, but for some reason I cannot fathom I had an old version of the jqGrid library. I had version 4.7 and the current version is 4.14.
With the right version it is now working.

How do I import a csv into chart.js?

I have been looking for this solution but can't seem to find it . Does chart.js support this ?
I have attempted to parse in the data with papaparse, but due to my limited knowledge I can't find a solution.
There is a Chart.js plugin chartjs-plugin-datasource that makes it easy to load data from CSV files.
Let's suppose you have a CSV file as shown below, and it is saved as sample-dataset.csv in the same directory as your HTML file:
,January,February,March,April,May,June,July
Temperature,7,7,10,15,20,23,26
Precipitation,8.1,14.9,41.0,31.4,42.6,57.5,36.0
Include Chart.js and chartjs-plugin-datasource in your page:
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource#0.1.0"></script>
<canvas id="myChart"></canvas>
Then, specify sample-dataset.csv in your script. By default, each row in a CSV file will be mapped to one dataset, and the first column and the first row will be treated as dataset labels and index labels respectively. You can also customize how to parse CSV data using options.
var ctx = document.getElementsById("myChart");
var chart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
type: 'line',
yAxisID: 'temperature',
backgroundColor: 'transparent',
borderColor: 'rgb(255, 99, 132)',
pointBackgroundColor: 'rgb(255, 99, 132)',
tension: 0,
fill: false
}, {
yAxisID: 'precipitation',
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'transparent'
}]
},
plugins: [ChartDataSource],
options: {
scales: {
yAxes: [{
id: 'temperature',
gridLines: {
drawOnChartArea: false
}
}, {
id: 'precipitation',
position: 'right',
gridLines: {
drawOnChartArea: false
}
}]
},
plugins: {
datasource: {
url: 'sample-dataset.csv'
}
}
}
});
Here is my solution that works fine for me. I have a CSV file like this:
country,population
China,1415046
India,1354052
United States,326767
Indonesia,266795
Brazil,210868
...
I want to plot a bar chart with my dataset, the y-axis is population and the x-axis is country.
This is the body of my HTML file.
<body>
<canvas id="myChart" width="100" height="100"></canvas>
<script>
// Load the dataset
d3.csv("data.csv").then(makeChart);
// Plot the data with Chart.js
function makeChart(countries) {
var countryLabels = countries.map(function (d) {
return d.country;
});
var populationData = countries.map(function (d) {
return d.population;
});
var chart = new Chart("myChart", {
type: "bar",
data: {
labels: countryLabels,
datasets: [
{
data: populationData
}
]
}
});
}
</script>
</body>
Result:
You can try it with Codesandbox.
I've had need to do something like this from time to time as well. Here's a link on how to create a chart with Chart.js from a CSV file that explains exactly how to create a chart with Chart.js directly from a CSV file.
The use case explains how to convert a CSV file to JSON using the Flex.io web service (Full disclosure: I'm the senior front end developer at Flex.io).
Here's a JsFiddle if you'd like to see the use case in action:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
$.ajax({
type: 'post',
url: 'https://www.flex.io/api/v1/pipes/flexio-chart-js-csv-to-json/run?stream=0',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer nmgzsqppgwqbvkfhjdjd');
},
data: $('form').serialize(),
dataType: "json",
success: function(content) {
// render the JSON result from from the Flex.io pipe
$("#flexio-result-data").text(JSON.stringify(content, null, 2))
var first_item = _.get(content, '[0]', {})
var column_labels = _.map(_.omit(first_item, ['os']), function(val, key) {
if (key != 'os')
return key
})
// use Lodash to reformat the JSON for use with Chart.js
var datasets = _.map(content, function(item) {
// use the 'os' column as our label
var item_label = _.get(item, 'os', 'Not Found')
// create an array of number values from each item's JSON object
var item_values = _.map(_.omit(item, ['os']), function(val) {
return parseFloat(val)
})
return {
label: item_label,
data: item_values,
backgroundColor: getRandomColor()
}
})
var chart_data = {
labels: column_labels,
datasets: datasets
}
// render the JSON result after mapping the data with Lodash
$("#chart-data").text(JSON.stringify(chart_data, null, 2))
// render the chart using Chart.js
var ctx = document.getElementById("canvas").getContext("2d");
window.my_chart = new Chart(ctx, {
type: 'bar',
data: chart_data,
options: {
responsive: true,
legend: {
position: 'top'
},
title: {
display: true,
text: 'Use Flex.io to Create a Chart With Chart.js Directly From a CSV File'
}
}
});
}
});
Feel free to step through the use case and let me know if you have any issues.
The simple example of importing CSV data into ChartJS
index.html:
<!-- ChartJS plugin datasrouce example
chartjs-plugin-datasource: https://nagix.github.io/chartjs-plugin-datasource/
Samples: https://nagix.github.io/chartjs-plugin-datasource/samples/
Specific example: https://nagix.github.io/chartjs-plugin-datasource/samples/csv-index.html
Data source: https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv -->
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource#0.1.0"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script src="script.js"></script>
</body>
You can also download this index.html file as a gist.
script.js
// ChartJS plugin datasrouce example
// chartjs-plugin-datasource: https://nagix.github.io/chartjs-plugin-datasource/
// Samples: https://nagix.github.io/chartjs-plugin-datasource/samples/
// Specific example: https://nagix.github.io/chartjs-plugin-datasource/samples/csv-index.html
// Data source: https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv
var chartColors = {
red: 'rgb(255, 99, 132)',
blue: 'rgb(54, 162, 235)'
};
var color = Chart.helpers.color;
var config = {
type: 'bar',
data: {
datasets: [{
type: 'line',
yAxisID: 'temperature',
backgroundColor: 'transparent',
borderColor: chartColors.red,
pointBackgroundColor: chartColors.red,
tension: 0,
fill: false
}, {
yAxisID: 'precipitation',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: 'transparent'
}]
},
plugins: [ChartDataSource],
options: {
title: {
display: true,
text: 'CSV data source (index) sample'
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
id: 'temperature',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
labelString: 'Temperature (°C)'
}
}, {
id: 'precipitation',
position: 'right',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
labelString: 'Precipitation (mm)'
}
}]
},
plugins: {
datasource: {
type: 'csv',
url: 'https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv',
delimiter: ',',
rowMapping: 'index',
datasetLabels: true,
indexLabels: true
}
}
}
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
};
Here is a a gist with this script.js file.
Make sure that both files are in the same directory.
Open index.html with your browser.
Additional materials
CodeSandbox example to preview the example online.
Reason for posting this answer:
I posted this because people are having problems with reading CSV files from the filesystem (directly from the computer) with JavaScript. The examples in chartjs-plugin-datasource documentation don't explain this, and it is assumed that the user has some basic knowledge on the differences in handling URLs from the web, and files from the file system.
My example just shows the basic functionality of the ChartJS datasource plugin, no third-party modules for reading the CSV file are required.
Edit:
According to ggorlen's suggestion from the comment, I also included the code snippets in the answer itself.
Can't post comments on this elitist site, because four years hasn't gotten me enough "points." ....
#huy - interesting how your Codesandbox has completely different code than what you've posted which I found was directly ripped off from another site... it doesn't even relate to the chart you were talking about building. Within Codesandbox, all I see is an image file of the chart, nothing is actually working (and how could it, when the code isn't even related to your dataset!?).

ExtJS 3.0.0 autoreload json store

I need to reload my chart's json store automatically on interval of 2 minutes.
This is my code:
tab = new Ext.Panel({
id: "id-" + node.id,
closable: true,
title: node.attributes.text,
layoutConfig: {
columns: 3
},
defaults: {
frame: true,
height: 230,
border: true
},
items: [
new Ext.chart.LineChart({
store: new Ext.data.JsonStore({
url: 'dashboard/CantServicios',
root: 'cantservicio',
autoLoad: true,
ields: ['NOMBRE_SERVICIO', 'CANT']
}),
xField: 'NOMBRE_SERVICIO',
yField: 'CANT',
width: 840
})
]
});
How can I do that ?
You can do this using Ext.util.TaskRunner
http://docs.sencha.com/extjs/3.4.0/?mobile=/api/Ext.util.TaskRunner
So if you look at the sample in the docs link above you should see that you can easily define a function that just performs a load on your store and then it's just a matter of using that in as the run config option.

Sencha Touch not firing beforeshow event listener

Im new to sencha touch and going through the obligatory hair pulling and head2desk pounding.
Im trying to display a List but Im having a problem.
Im using a beforeshow event to load my json store before the list is displayed. But it's not firing the event. If any can help it is MOST appreciated.
My code is as follows: *note- this code is AS/400 centric so the /%...%/ is for that
function doList() {
var List1 = new Ext.List ({
id : List1,
renderTo : 'panel',
fullscreen: true,
showAnimation: {
type: 'slide',
duration: 250
},
cls: 'demo-list',
width: Ext.is.Phone ? undefined : 300,
height: 500,
store: ListStore,
itemTpl: '<strong>{SCEQPT}</strong>',
grouped: true,
indexBar: true,
onItemDisclosure: function(record, btn, index) {
doPopUp(record);
},
listeners: {
'beforeshow': function () {
alert('beforeshow');
var StoreList = Ext.StoreMgr.get('ListStore'
StoreList.load({
params: {
screfr: Ext.getCmp('SCREFR').getValue(),
scptyp: scptyp,
user : '/%SCUSER%/'
}
});
}
}
});
}
beforeshow listener is triggered only when you are displaying an item with show() method.
Try using the listeners
'render','beforerender' and 'afterrender'. instead.