JSON Data not displaying in ng-grid in angular - asp.net

I've got a controller that makes an HTTP Call to the database. It returns the data, verified by the $log command but does not display it in the grid. Here's the code..
Thanks in advance...
eventsApp.controller('TerrController',
function TerrController($scope, territoryData) {
$scope.territory = [];
//$scope.gridOptions = {
// data: 'territory', columnDefs: [
// { field: 'TerritoryID', displayName: 'ID'},
// { field: 'TerritoryDescription', displayName: 'Description' },
// { field: 'RegionID', displayName: 'RegionID' }]
//};
territoryData.getTerritories().then(function (response) {
var tmpData = angular.fromJson(response);
$scope.territory = tmpData;
});
$scope.gridOptions = {
data: 'territory', columnDefs: [
{ field: 'RegionID', displayName: 'RegionID', visible: true },
{ field: 'TerritoryDescription', displayName: 'Description', visible: true },
{ field: 'TerritoryID', displayName: 'ID', visible: true }]
};
});
eventsApp.factory('territoryData', function ($http, $q, $log) {
return {
getTerritories: function () {
var deferred = $q.defer();
$http({ method: 'GET', url: '/Home/GetTerritories' }).
success(function (result, status, headers, config) {
angular.forEach(result, function (c) {
$log.log(c.TerritoryDescription);
});
deferred.resolve(result);
}).
error(function (result, status, headers, config) {
deferred.reject(status)
});
return deferred.promise;
}
}
});

Related

Ajax and error cannot read properties of undefined

So I am trying to get some data from a table using ajax but this error keeps popping up and I know its related to parameters but I have none of the parameters it says are wrong anyone got any ideas?
I am working in asp.net 6 and am trying to get the data to a controller.
I am currently working in C# and ajax
(function () {
"use strict"
window.onload = function () {
//Reference the DropDownList.
var ddlYears = document.getElementById("ddlYears");
//Determine the Current Year.
var currentYear = (new Date()).getFullYear() + 10;
var less = (new Date()).getFullYear() - 10;
//Loop and add the Year values to DropDownList.
for (var i = less; i <= currentYear; i++) {
var option = document.createElement("OPTION");
option.innerHTML = i;
option.value = i;
ddlYears.appendChild(option);
}
};
var ScopeTable;
$(document).ready(function () {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
},
{
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
}
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
}
});
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
$("#spnrSave").hide();
});
function btnAddEditScope_click() {
console.log("button clicked")
$.ajax({
url: "Scope/AddEditScope",
type: "GET",
success: function () {
$("#vw_AddEditScope").modal("show");
}
});
}
}());
Error that is being posted
Figured it out just had do adjust my ajax and it worked fine. The tutorial I found is here https://datatables.net/examples/api/multi_filter.html
var ScopeTable;
$(document).ready(function (e) {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
}, {
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
},
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
},
error: function (e) {
console.log(e);
}
});
$('#tblScopeView tfoot th').each(function () {
var title = $("#tblScopeView").eq($(this).index()).text();
$(this).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
ScopeTable.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
});
$("#spnrSave").hide();
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
});

Symfony and FullCalendar, how to send data from database

I'm trying to use FullCalendar.io with tattali/calendar-bundle.
I want to display a calendar for a lending objects service.
So the calendar must show the days during which one object is unavialable.
The problem is I can't manage to send the object to fullcalendar so I can get the reservations and the days the object is reserved.
Here is my code for the Javascript :
document.addEventListener("DOMContentLoaded", () => {
var calendarEl = document.getElementById("calendar");
var calendar = new Calendar(calendarEl, {
plugins: [interactionPlugin, dayGridPlugin, timeGridPlugin, listPlugin],
headerToolbar: {
left: "prev,next",
center: "title",
right: "dayGridMonth,listWeek",
},
buttonText: {
today: "Today",
month: "month",
week: "week",
day: "day",
list: "list",
},
displayEventTime: false,
initialDate: Date.now(),
locale: "fr",
firstDay: "1",
// editable: true,
// dayMaxEvents: true,
eventSources: [
{
url: "/fc-load-events",
method: "POST",
extraParams: {
filters: JSON.stringify({}),
},
failure: () => {
console.log("There was an error while fetching FullCalendar!");
},
},
{
url: "/json-feed",
method: "POST",
extraParams: {
filters: JSON.stringify({}),
},
failure: () => {
console.log("There was an error while fetching FullCalendar!");
},
}
],
events: [
{
groupId: "association ouverte", // recurrent events in this group move together
daysOfWeek: ["3", "6"],
display: "background",
color: "#5c995e",
},
],
timeZone: "UTC",
});
calendar.render();
});
The Symfony controller :
// controller for displaying the page :
#[Route('/object-details/{slug}', name: 'object-details', methods: ['GET', 'POST'])]
public function detailsObject(
Object $object,
LoanRepository $loan,
): Response {
return $this->render('home/details-object.html.twig', [
'controller_name' => 'HomeController',
'object' => $object,
'loan' => $loan,
]);
}
// controller for getting json :
#[Route('/json-feed', name: 'json-feed')]
public function getJson(Request $request): JsonResponse
{
$response = new JsonResponse(['objet' => 12]);
dump($response);
return $response;
}
The json-feed route works but I don't know how to send the object details with it.
Thanks for any help.
Well I managed to do it that was pretty easy !
I was trying to send the object's data as a json but I just needed to get it with some jquery on the dom.
I did this :
//...
document.addEventListener("DOMContentLoaded", () => {
var calendarEl = document.getElementById("calendar");
// I get the object id from the dom :
var object = $("#objet-calendar").find('p').text();
//...
then I added it to the filters :
//...
{
url: "/fc-load-events",
method: "POST",
extraParams: {
filters: JSON.stringify({'object' : object}),
},
failure: () => {
console.log("There was an error while fetching FullCalendar!");
},
},
//...
Finally in onCalendarSetData()
//...
public function onCalendarSetData(CalendarEvent $calendar, $router)
{
$start = $calendar->getStart();
$end = $calendar->getEnd();
$filters = $calendar->getFilters();
$object = $this->objectRepo->findOneById($filters);
$object_id = $objet->getId();
//...
And it works

FullCalender 5 Unable to render dynamic events & resources

I am trying to render events and resources which are stored in a database. I can get the calendar to render with predefined data for events and resources, however when I push data into the array's, the new objects do not appear when the calendar is rendered.
This is the JS code I am using to obtain the data and render the calendar;
function GetCalenderDetails() {
$.ajax({
url: 'myapiendpoint',
type: 'GET',
success: function (response) {
$.each(response.bookedServices, function (i, v) {
services.push({
id: v.id,
title: v.title
});
});
console.log(JSON.stringify(services));
$.each(response.userBookings, function (i, v) {
bookings.push({
id: v.id,
resourceId: v.resourceId,
title: v.title,
start: v.start,
allDay: v.allDayFlag
});
});
console.log(JSON.stringify(bookings));
calendar.render();
},
error: function (error) {
console.log(error);
}
});
}
var bookings = new Array({ id: '1', resourceId: 'a', title: 'Meeting', start: '2021-03-14', allDay: true });
var services = new Array({ id: 'a', title: 'Room A' });
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
timeZone: 'UTC',
initialView: 'resourceTimelineDay',
aspectRatio: 1.5,
headerToolbar: {
left: 'prev,next',
center: 'title',
right: 'resourceTimelineDay,resourceTimelineWeek,resourceTimelineMonth'
},
editable: true,
resourceAreaHeaderContent: 'Resources',
resources: services,
events: bookings
});
GetCalenderDetails();
The following is the console output of the 'services' and 'bookings' variables after the GetCalenderDetails function is executed;
Resources Output
[{"id":"a","title":"Room A"},{"id":"b","title":"Room B"}]
Events Output
[{"id":"1","resourceId":"a","title":"Meeting","start":"2021-03-14","allDay":true},
{"id":"2","resourceId":"b","title":"Meeting B","start":"2021-03-15","allDay":true}]
The first resource and event will render, however the second item which is pushed into the array from the GetCalenderDetails function do not render.
I am probably missing something very obvious, but I am not seeing it, so another set of eyes might help :)
As suggested by ADyson's comments, here is the solution to my problem just in case anyone else ends up in the same position;
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
timeZone: 'UTC',
initialView: 'resourceTimelineDay',
headerToolbar: {
left: 'prev,next,today',
center: 'title',
right: 'resourceTimelineDay,resourceTimelineWeek,resourceTimelineMonth'
},
editable: true,
resourceAreaHeaderContent: 'Booked Services',
resources: function (info, successCallback, failureCallback) {
$.ajax({
url: 'myapiendpoint',
type: 'GET',
success: function (response) {
var resources = [];
console.log(response);
if (response.status == true) {
$.each(response.bookedServices, function (i, v) {
resources.push({
id: v.id,
title: v.title
});
});
} else {
//Do something
}
return successCallback(resources);
},
error: function (error) {
console.log(error);
}
});
},
events: function (info, successCallback, failureCallback) {
$.ajax({
url: 'myapiendpoint',
type: 'GET',
success: function (response) {
var events = [];
console.log(response);
if (response.status == true) {
$.each(response.userBookings, function (i, v) {
events.push({
id: v.id,
title: v.title,
start: v.start,
allDay: v.allDayFlag
});
});
} else {
//Do something
}
return successCallback(events);
},
error: function (error) {
console.log(error);
}
});
}
});
calendar.render();

update/delete event for Kendo UI Grid Aurelia

The update/create/delete events are not getting fired. Any idea?
View:
<ak-grid k-option.bind = "gridOptions" id="adminGrid" k-toolbar.bind="['create']" k-editable.bind="true" k-pageable.bind="true" k-sortable.bind="true">
</ak-grid>
View Model:
activate(params) {
this.name = params.type.toUpperCase();
return this.getData(this.getType(), null).then(items => {
this.getMetadata(items)
.then(metadata => {
this.gridOptions = metadata;
});
});
}
getMetadata(items) {
return new Promise(resolve => {
resolve({
columns: this.getColumns(items),
autoSync: true,
dataSource: {
transport: {
read: //alert("read"),
function (e) {
e.success(items);
},
update:
function (e) {
alert("update"),
e.success(e.data);
},
destroy: function (e) {
alert("delete");
},
parameterMap: function (options, operation) {
if (operation == "create") {
alert("create param");
}
return options;
}
},
pageSize: 10,
editable: true,
pageable: {
refresh: true,
pageSizes: true
}
}
});
});
}

Error when updating an object in auto-form with meteor

I have checked the docs but I cannot get my head around this. I have an object that I want to update using Auto-Form and Collections2 with meteor.
//Schema
Records = new Mongo.Collection('records');
var Schemas = {};
Schemas.Record = new SimpleSchema({
title: {
type: String,
label: "Title",
max: 200
},
caption: {
type: String,
label: "Caption",
max: 200
},
text: {
type: String,
label: "Detailed text",
optional: true,
max: 1000
},
loc: {
type: Object,
optional: true,
blackbox: true
},
createdAt: {
type: Date,
autoform: {
type: "hidden"
},
autoValue: function() {
if (this.isInsert) {
return new Date;
}
else if (this.isUpsert) {
return {
$setOnInsert: new Date
};
}
else {
this.unset();
}
}
},
updatedBy: {
type: String,
autoValue: function() {
return Meteor.userId();
}
}
});
Records.attachSchema(Schemas.Record);
I have a hook so that I assign the object before update
AutoForm.hooks({
insertCommentForm: {
before: {
insert: function(doc) {
doc.commentOn = Template.parentData()._id;
return doc;
}
}
},
updateRecordForm: {
before: {
update: function(doc) {
console.log("storing location data");
doc.loc = Session.get('geoData');
console.log(doc.loc);
return doc;
}
}
}
});
I get this error.
Uncaught Error: When the modifier option is true, all validation
object keys must be operators. Did you forget $set?
I don't know how to "$set" with autoform.
when you are trying to update a document in Mongo, when you want to update only certain fields, you will use the $set modifier.
Records.update({ _id: 1 }, { $set: { loc: { lat: 12, lng: 75 } } })
The above would update only the loc value.
Records.update({ _id: 1 }, { loc: { lat: 12, lng: 75 } })
The above would remove all other keys and the record will only have the _id and the loc.
Your hook will have to set the loc key in doc.$set.
Please update your hook with the following code and it should work:
updateRecordForm: {
before: {
update: function(doc) {
console.log("storing location data", doc);
doc.$set.loc = Session.get('geoData');
return doc;
}
}
}

Resources