Error in syncing data from google calendar to Jquery Full calendar - fullcalendar

I have a task that, need to sync my websites's full calendar with google calendar private data. I could able to extract data from google, but while trying to display that to the Jquery full calendar, it shows an error that TypeError: $(...).fullCalendar is not a function, but when page loads full calender is loading properly. I'm getting this error only when refreshing the calendar after fetching data from google.
Here is the code i'm using:
<!DOCTYPE html>
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset='utf-8' />
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css' />
</head>
<body>
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<div id='calendar'></div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.js'></script>
<script type="text/javascript">
var events = [];
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
events: events,
color: 'black', // an option!
textColor: 'yellow' // an option!
}
// any other event sources...
]
});
var CLIENT_ID = 'My Id';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listUpcomingEvents();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
function refreshCalander(eventData) {
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
events: eventData,
color: 'black', // an option!
textColor: 'yellow' // an option!
}
// any other event sources..
]
});
}
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function (response) {
var googleEvents = response.result.items;
if (googleEvents.length > 0) {
for (i = 0; i < googleEvents.length; i++) {
var event = googleEvents[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
events.push({ "title": event.summary, "start": when });
}
refreshCalander(events);
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>

Related

How Disable Browser Back Button only after 1 minits

How Disable Browser Back Button only after 1 minits
<script type = "text/javascript" >
function preventBack() { window.history.forward(1); }
setTimeout("preventBack()", 0);
window.onunload = function () { null };
It deactivates completely
I just want to disable go back for a minute
example: https://www.arabpage.net/
You are close. You can combine addEventListener on load with the onbeforeunload. And then we delay it with a setTimeout.
<script type="text/javascript">
window.addEventListener( "load", function() {
setTimeout( function() {
return;
}, 10000 ); // ... 10000ms = 10s, 60 000ms = 1min
window.onbeforeunload = function() {
return ""; }
} );
</script>
Edit
As per your comments.
<script type="text/javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (3) }
</script>
Learn more
onbeforeunload # https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
load # https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

fullcalendar events not displayed after next

I'm trying to replace my old calendar (DHX) by full calendar.
I use the demo code, and i managed to display my json events.
The issue i have is when i click to NEXT, or PEV.
I don,t see the others events.
I load all 2019 events in one shot for the next events should be displaying.
HTML :
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>FTS Team</title>
<script type="text/javascript" src="lib/angular.js"></script>
<script type="text/javascript" src="lib/angular-resource.js"></script>
<script src="calendarv2.js"></script>
<link rel="stylesheet" href="http://angular-ui.github.io/ui-calendar/bower_components/bootstrap-css/css/bootstrap.css">
<link rel="stylesheet" href="lib/bootstrap/css/bootstrap-theme.min.css">
<script src="lib/jquery-1.11.1.min.js"></script>
<script src="lib/bootstrap/js/bootstrap.min.js"></script>
<!-- For Calendar -->
<script src="http://angular-ui.github.io/ui-calendar/bower_components/moment/moment.js"></script>
<script src="http://angular-ui.github.io/ui-calendar/bower_components/fullcalendar/dist/fullcalendar.js"></script>
<script src="http://angular-ui.github.io/ui-calendar/bower_components/fullcalendar/dist/gcal.js"></script>
<script src="http://angular-ui.github.io/ui-calendar/src/calendar.js"></script>
<link rel="stylesheet" href="http://angular-ui.github.io/ui-calendar/bower_components/fullcalendar/dist/fullcalendar.css">
<!-- For Modal Windows -->
<script src="lib/bootstrap/js/ui-bootstrap-tpls-0.11.0.js"></script>
</head>
<body ng-controller="myCtrl">
<div ui-calendar="uiConfig.calendar" class="span12 calendar" ng-model="eventSources"></div>
</body>
</html>
The JS is :
var app = angular.module('myApp', ['ui.calendar', 'ui.bootstrap']);
app.controller('myCtrl', function ($scope, $http, $compile, uiCalendarConfig)
{
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
/* event source that contains custom events on the scope */
$scope.events = [{title: 'All Day Event',start: new Date(y, m, 1)}];
$http.get('rest/event/').success(function(data) {
$scope.myEvents = data;
data.forEach(function(entry) {
var d1 = new Date(entry["dateB"]);
var d2 = new Date(entry["dateE"]);
var myEvent = {title: entry["title"],start: d1, end: d2, allDay: true};
if ( d1.getFullYear() >= 2019 ) {
$scope.events.push(myEvent);
}
});
});
/* alert on eventClick */
$scope.alertOnEventClick = function( date, jsEvent, view){
$scope.alertMessage = (date.title + ' was clicked ');
alert(date.title + ' was clicked ');
};
/* alert on Drop */
$scope.alertOnDrop = function(event, delta, revertFunc, jsEvent, ui, view){
$scope.alertMessage = ('Event Droped to make dayDelta ' + delta);
};
/* alert on Resize */
$scope.alertOnResize = function(event, delta, revertFunc, jsEvent, ui, view ){
$scope.alertMessage = ('Event Resized to make dayDelta ' + delta);
};
/* Change View */
$scope.changeView = function(view,calendar) {
alert("change View");
uiCalendarConfig.calendars[calendar].fullCalendar('changeView',view);
};
/* Change View */
$scope.renderCalender = function(calendar) {
alert("change View render");
if(uiCalendarConfig.calendars[calendar]){
uiCalendarConfig.calendars[calendar].fullCalendar('render');
}
};
/* Render Tooltip */
$scope.eventRender = function( event, element, view ) {
element.attr({'tooltip': event.title,'tooltip-append-to-body': true});
$compile(element)($scope);
};
/* config object */
$scope.uiConfig = {
calendar:{
height: 600,
editable: false,
weekends: true,
defaultView: 'month',
lazyFetching: 'false',
displayEventTime: false,
header:{
left: 'title',
center: '',
right: 'today prev,next'
},
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.eventRender
}
};
/* event sources array*/
$scope.eventSources = [$scope.events];
});
Would have any idea what i'm missing ?
thanks,
Nicolas
I had the same problem and I destroyed the callender and then recreate it for next and prev event ,and its work for me!

Problem in making chart with Chart.js in wix?

I am having a problem in building a pie chart with chart.js ..I am working in wix.com ..The problem i am facing is with 2 postmessage()..
Here is the page code....
import wixData from 'wix-data';
import { session } from 'wix-storage';
var name = session.getItem('name');
var platformName = session.getItem('platform');
import { getchampionranks } from 'backend/pcprofile.jsw';
$w.onReady(function () {
getchampionranks('pronil07').then(res => {
console.log(res);
var data = [];
var labels = [];
for (var i = 0; i <= res.length - 1; i++) {
data.push(res[i].Minutes.toString());
labels.push(res[i].champion.toString());
}
console.log(data);
console.log("Data length: " + data.length);
console.log(labels);
console.log("Label length: " + labels.length);
$w("#html1").postMessage(data);
//$w("#html1").postMessage(labels);
});
});
Here is the iframe code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="146" height="149"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [],
datasets: [{
label: 'wins/loss',
data: [],
backgroundColor: [
'#3ddba1',
'#e02a2a',
'#4286f4',
'#6897e2',
'#444a54',
'#45a567',
'#91a545',
'#a87534',
'#8c6e8a'
],
borderWidth: 1
}]
},
options: {
cutoutPercentage : 0,
rotation: Math.PI * 0.8,
legend:{
display: false,
position: 'bottom',
},
animation: {
easing: 'easeOutElastic',
Steps: 100,
animateRotate : true,
animateScale : true
}
}
});
window.onmessage = function(event){
myChart.data.datasets[0].data = event.data;
myChart.update();
};
function ready(){
window.parent.postMessage({"type":"ready"}, "*");
}
</script>
</body>
</html>
On doing this..i am getting the result like this..
Result
I am getting the chart with the data array..but the labels is undefined..
And if i unquote the postmessage(labels) and send both data and labels via 2 postmessage()..the chart don't form...
I need to send both data and labels array to the iframe from page code...
Any solution?????
This is easiest done by sending both the data and the labels from your page code in one object. Then in the HTML element, you can set the chart's data and labels using that object.
In your case, that would look something like this:
Page Code:
let info = {data:data, labels:labels};
$w("#html1").postMessage(info);
HTML Element Code:
window.onmessage = function(event){
myChart.data.datasets[0].data = event.data.data;
myChart.data.labels = event.data.labels;
myChart.update();
};
You are right! This is the easiest way.
Here is the page code...
var data = [];
for (var i = 1; i < 7; i++) {
var _temp = Math.log10(i);
data.push(_temp);
}
var labels = ["September", "October", "Novemver", "December", "January", "February"];
$w.onReady(() => {
console.log("Data length: " + data.length);
console.log(data);
console.log("Label length: " + labels.length);
console.log(labels);
$w("#html1").onMessage((event) => {
let info = { data: data, labels: labels };
if (event.data.type === 'ready') {
$w("#html1").postMessage(info);
}
});
});
Here is the html code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js">
</script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="250" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Our activity',
data: []
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
window.onmessage = function(event){
myChart.data.datasets[0].data = event.data.data;
myChart.data.labels = event.data.labels;
myChart.update();
};
function ready(){
window.parent.postMessage({"type":"ready"}, "*");
}

How import file Excel to multiple tables in DB using asp.net and angularJS?

I have developed an application, and in this application I want to import file Excel to multiple table in my DB, and since i am a beginner in angularJS and .NET, I work with .net web api and angularjs, and I develop a function, it works when I import the data into a singe table, but the problem how to import the data into 3 table in DB !!! . and the 3 tables are linked to each other (in my exemple code there 2 table Candidature and Candidat). My question is: how to import Excel file to multiple table in DB and thank's. ( i work with asp.net web API and angularJS )
controller.cs:
/////
[Route("api/Candidature/SaveData")]
[HttpPost]
[ResponseType(typeof(Candidat))]
public IHttpActionResult SaveData(List<Candidature> Candidatures, List<Candidat> candidat)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (var data in Candidatures)
{
db.Candidature.Add(data);
}
db.SaveChanges();
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
db.SaveChanges();
return StatusCode(HttpStatusCode.OK);
////
service.js:
SaveData: {
method: 'POST' ,
url: serviceBase + 'Candidature/SaveData',
isArray: true,
headers: {
'Content-Type' : 'application/json'
}
},
CandidatureCtrl.js :
$scope.Importation = function (data) {
$scope.SelectedFileForUpload = null;
$scope.UploadFile = function (files) {
$scope.$apply(function () { //I have used $scope.$apply because I will call this function from File input type control which is not supported 2 way binding
$scope.Message = "";
$scope.SelectedFileForUpload = files[0];
})
};
//Parse Excel Data
$scope.ParseExcelDataAndSave = function () {
var file = $scope.SelectedFileForUpload;
if (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
//XLSX from js-xlsx library , which I will add in page view page
var workbook = XLSX.read(e.target.result, { type: 'binary', cellDates:true, cellStyles:true });
var sheetName = workbook.SheetNames[0];
var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if (excelData.length > 0) {
//Save data
Candidature.SaveData(excelData).then(function (data) {
if (data.status) {
$scope.Message = excelData.length + " record inserted";
}
else {
$scope.Message = "Failed";
}
}, function (error) {
$scope.Message = "Error";
});
// Candidature.SaveDatacandidature(excelData).then(function (data) {
// if (data.status) {
// $scope.Message = excelData.length + " record inserted";
// }
// else {
// $scope.Message = "Failed";
// }
// }, function (error) {
// $scope.Message = "Error";
// });
// $scope.SaveData(excelData);
}
else {
$scope.Message = "No data found";
}
}
reader.onerror = function (ex) {
console.log(ex);
}
reader.readAsBinaryString(file);
}
};
var dialogOpts = {
backdrop: 'static',
keyboard: false,
scope: $scope,
size: 'lg',
templateUrl: 'views/candidature/Importation.html',
controller: ['$scope', '$uibModalInstance','$sce',
function ($scope, $uibModalInstance, $sce) {
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
]
};
$uibModal.open(dialogOpts);
};
Importation.html :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
<script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<!--<script src="app/views/candidature/candidatureCtrl.js"></script>-->
</head>
<body ng-app="agu">
<div ng-controller="candidatureCtrl" class="container" style="margin-top:50px;">
<div class="form-inline">
<input type="file" name="file" class="form-control"
onchange="angular.element(this).scope().UploadFile(this.files)"/>
<input type="button" value="Import" class="btn btn-success" ng-disabled="!SelectedFileForUpload"
ng-click="ParseExcelDataAndSave()" />
<br/>
<span style="color:red">
{{Message}}
</span>
</div>
</div>
</body>
</html>
In your web api, you are expecting two arrays for Candidatures and candidat.
But from your controller you are passing only one array of data excelData.
So when it comes to api it doesn't execute this code,
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
Because candidat is either null or undefined. So it can't go through the loop which the below code is never executed.
db.Candidat.Add(data);

How do I track SignalR Connection State?

I was pointed to this GITHub sample code by David Fowler himself to track SignalR users and states. I have implemented all of it and it works great except I can't figure out the displaying of Hub connection state changes. I have this which doesn't seem to work. Does anyone know why?
!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
#state {
width: 20px;
height: 50px;
}
</style>
</head>
<body>
<h3 id="msg"></h3>
<div id="state"></div>
<script src="../Scripts/jquery-1.10.2.min.js"></script>
<script src="../Scripts/jquery.signalR-2.0.2.min.js"></script>
<script src="signalr/hubs"></script>
<script>
$(function () {
var userTracking = $.connection.alphaHub;
// Need at least one callback for events to be raised on the hub
userTracking.client.void = function () { };
$.connection.logging = true;
$.connection.hub.stateChanged(function (change) {
if (change.newState === $.signalR.connectionState.connected) {
$('#state').css('background-color', 'green');
} else if (change.newState === $.signalR.connectionState.reconnecting) {
$('#state').css('background-color', 'yellow');
} else if (change.newState === $.signalR.connectionState.disconnected) {
$('#state').css('background-color', 'red');
}
});
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 1000);
});
});
</script>
</body>
</html>
My Hub is shown partially here:
public class AlphaHub : Hub
{
public override async Task OnConnected()
{
try
{
var name = Context.User.Identity.Name;
using (savitasEntities2 entities = new savitasEntities2())
{
var user = entities.SUsers
.Include(u => u.SConnections)
.SingleOrDefault(u => u.UserName == name);
if (user == null)
{
user = new SUser
{
UserName = name,
SConnections = new List<SConnection>()
};
entities.SUsers.Add(user);
}
user.SConnections.Add(new SConnection
{
ConnectionID = Context.ConnectionId,
UserAgent = Context.Request.Headers["User-Agent"],
LastActivity = DateTimeOffset.UtcNow
});
// entities.SaveChanges();
await entities.SaveChangesAsync();
}
}
public override async Task OnDisconnected()
{
try
{
using (savitasEntities2 db = new savitasEntities2())
{
var connection = await db.SConnections.FindAsync(Context.ConnectionId);
db.SConnections.Remove(connection);
await db.SaveChangesAsync();
}
}
catch (Exception ex)
{
c.LogError(ex.Message, "AlphaHub.cs" + " - " + this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
}
}
Looks like your hubs can't be found.
Change:
<script src="signalr/hubs"></script>
to:
<script src="~/signalr/hubs"></script>

Resources