DataTables warning: table id=patients - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1 - asp.net-mvc

I have Issue with this Datatable Jquery i get this Error:DataTables warning: table id=patients - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
I do this Function on controller:
[HttpGet]
public JsonResult LoadPatients()
{
// Browser list
var totalPatientsList = _unitOfWork.Patients.GetPatients();
var filteredResult = from b in totalPatientsList
select new[] {b.Jeton, b.Nom, b.TelePhone, b.Adresse, b.Villes.Nom,b.Id.ToString()};
return Json(new
{
data =filteredResult
},
JsonRequestBehavior.AllowGet);
}
and i call on index view :
$(document).ready(function () {
var table = $("#patients").DataTable({
ajax: {
url:"/patients/LoadPatients",
dataSrc: ""
},
columns: [
{
data: "jeton"
},
{
data: "nom"
},
{
data: "telephone",
render: function (data) {
return data.toString().replace(
/(\d\d\d)(\d\d\d)(\d\d\d\d)/g, '$1-$2-$3');
}
},
{
data: "adresse"
},
{
data: "villes.nom"
},
{
data: "id",
render: function (data, type, patient) {
return "<a href='/patients/details/ " + patient.id + "' class='btn btn-default btn-xs'>" + "<i class='fa fa-folder'></i>View</a>" +
//"<button class= 'btn-link js-detail' data-detail-id=" + data + "><i class='fa fa-pencil-square'></i></button>" +
"<button class= 'btn btn-danger btn-xs js-delete' data-patient-id=" + data + "><i class='fa fa-trash-o'></i>Delete</button>";
}
}
]
});
I inspect result on chrome i get that:
{
"data": [
["0002020", "patienta", "0670707070", "Zone franche", "Tan", "1"],
["0002029", "tst", "0524242424", "Ma", "M", "10"]
]
}
How can i resolve this Issue thanks in advance

Your JSON does not have any labels - each row is just a data array, for example:
["0002020", "patienta", "0670707070", "Zone franche", "Tan", "1"]
This means you cannot use data labels like this:
data: "jeton"
because the label jeton does not exist in your JSON data.
So, instead, you can change all of these data:... values to title"... - for example:
title: "jeton"
This means that the first value in the array (which is "0002020") will appear in the first column of your table - and the column heading will be "jeton".
And then the second column in your table will contain "patienta" and will use the column heading of "nom" - and so on.
Here is my example using your data:
I think that is all you need to do to fix the issue.
Extra Notes:
Don't forget to update the ajax URL - it loos like you may have already done that.
You may also need to remove the following dataSrc: "" line from the ajax section, so it is this:
ajax: {
url:"/patients/LoadPatients"
},
but I am not sure. Try it both ways.

Related

ui-grid rowTemplate: how to dynamically change row color based on column data

I have a server data embedded with values that determine the row-color.
var ngBody = angular.module ('BodySpace', [
'ui.grid', 'ngSanitize', 'ngResource'
, 'ui.grid.selection', 'ui.bootstrap'
, 'ui.grid.resizeColumns'
]);
ngBody.controller('ngController', function($scope, $http, $filter, uiGridConstants) {
angular.element(document).ready(function () {
initScope( $scope, uiGridConstants, $filter);
$scope.Get2Data();
} );
initScope( $scope, uiGridConstants, $filter);
$scope.Get2Data = function() {
$scope.uiGrid306.data = serverdata;
:
:
:
}
})
The requested data from the server has a column that controls the row color. What should I write in my row template to reference my data column that determines each row's color to render?
On initiating your ui-grid, you will apply a row-template in which you execute the code referencing your column data that decide the row-color - here in this example, it is _ab_x_style which stores the name of my style class.
function initGrid( $scope, uiGridConstants, $filter){
$scope.uiGrid306 = {
rowTemplate: 'rowTemp.html'
, columnDefs: [{
field: 'FIELD1', name: 'my field name', width: "7%"
, filter: { type: uiGridConstants.filter.SELECT, selectOptions: Opts }
}, { ...
}, { ...
}]
}
}
You place your rowTemp.html where your .html page is. In your rowTemp.html, you have
<div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.uid" ui-grid-one-bind-id-grid="rowRenderIndex + '-' + col.uid + '-cell' " class="ui-grid-cell" ng-class="row.entity._ab_x_style" role="{{col.isRowHeader ? 'rowheader' : 'gridcell' }}" ui-grid-cell></div>
plunker

Set value of ng-select2 on a button click

The scenario is, I need to set the value of the dropdown (ng-select2) when a user presses on edit button present on the page. I am using ajax to fetch the options. The code is in angular.
I took reference from : https://github.com/tealpartners/ng-select2
<div class="form-div">
<label for="uploader">Select Uploader<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="uploader" id="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
<div class="form-div">
<label for="uploader">Select Approver<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="approver" [id]="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
</div>
setSelect2Options() {
this.select2Options = {
triggerChange: true,
allowClear: true,
placeholder : 'Select User* ',
minimumInputLength: 3,
ajax: {
url: '/api/reward/uploader/approver/search/user?limit=15',
headers: {
'X-XSRF-TOKEN': sessionStorage.getItem("auth"),
'content-type': 'application/json'
},
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term, page) {
return {
q: term.term, // search term
_: term._type
};
},
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
id: item.id,
text: item.name + " - " + item.email
}
})
};
}
},
//[placeholder]="'Select User* '"
}
}
The above codes are well and good. But now on a button click i need to set a value inn the select box.
this.vcDataService.getUploaderAproverDetails(id).subscribe((res: any) => {
this.uploaderApproverForm.controls['approver'].setValue(res.approverDetails.uploaderUserId);
this.uploaderApproverForm.controls['uploader'].setValue(res.uploaderDetails.approverUserId);
console.log("134", res)//uploaderUserId
//this.select2Options.ajax.processResults.push({id: 103, text: "aa"})
this.select2Options.placeholder="aa";
//this.displayUploader = "aaa";
// $('#uploader').val('ENABLED_FROM_JS');
// $('#uploader').trigger('change');
// this.select2Options.templateSelection = {
// selected: true,
// id: res.approverDetails.approverUserId,
// text: res.approverDetails.approverName,
// title: res.approverDetails.approverName
// }
// this.select2Options.initSelection = {
// callback: {
// data: {"id":103, "text":'ENABLED_FROM_JS'}
// }
// }
console.log(this.select2Options);
this.updateApproverUploader = true;
this.uploaderApproverId = res.uploaderApproverId;
this.cd.detectChanges();
},
err => {
Swal.fire('Oops...', err.error.err, 'error');
})
I tried few things but didn't got the workaround.
After going through the documentation I found a solution for it. I used the data attribute of the ng-select2 and assigned it to a Select2OptionData type variable.
import { Select2OptionData} from 'ng-select2';
patch_panel_array: Select2OptionData[];
Then I added the required data which I needed to show in the field as displayed below:
res.panelApprovers.map(item => {
this.patch_panel_array.push({
id: item.panelApproverUserId,
text: item.panelApproverUserName + " - " + item.panelApproverUserEmail
})
approverIds.push(String(item.panelApproverUserId));
});
this.formData.controls['panelApprover'].setValue(approverIds);
And here is my select 2 field:
<ng-select2 formControlName="panelApprover" [data]="patch_panel_array" [options]="select2OptionsPanel" width="100%" style="width: 100%;">
</ng-select2>

Populate Select2 field in Edit form

I'm a hobbyist developer. I'm using basic Select2 ajax in a new/edit Rails form, and I can't figure out how to re-populate it in the edit form. song_creditor_1 is a string, but it's entered as an id of Fan model.
form:
<%= f.input :song_creditor_1, label: 'Song Creditor 1', as: :select, input_html: { id: "song_creditor_1", include_hidden: false } %>
script
function templateDropDownFormat (item) {
return item.text;
}
function templateSelectionFormat (item) {
return item.text;
}
$("#song_creditor_1").select2({
placeholder: "Search",
ajax: {
url: "/songs",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data, function(cnut) {
return {
text: cnut.name + ", " + cnut.city + ", " + cnut.country + " (" + cnut.account_type + ")",
id: cnut.id,
};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: templateDropDownFormat, // omitted for brevity, see the source of this page
templateSelection: templateSelectionFormat// omitted for brevity, see the source of this page
});
Well, I'm just a hobbyist, and this is my first website, so this answer isn't pretty but it's how I resolved it. The issue was having to re-populate the data in the field if there was an error on the form, so I just pulled that particular attribute out during the 'create' and called it #creditor1.
var $select1 = $('#song_creditor_1');
function templateDropDownFormat (item) {
return item.text;
}
function templateSelectionFormat (item) {
return item.text;
}
$select1.select2({
ajax: {
url: "/songs",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data, function(cnut) {
return {
text: cnut.name + ", " + cnut.city + ", " + cnut.country + " (" + cnut.account_type + ")",
id: cnut.id,
};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: templateDropDownFormat, // omitted for brevity, see the source of this page
templateSelection: templateSelectionFormat// omitted for brevity, see the source of this page
});
<% if params[:action] === "edit" && #creditor1_real || params[:action] === "update" && #creditor1_real %>
var $option1 = $('<option selected><%= #creditor1_real.name %>, <%= #creditor1_real.city %>, <%= #creditor1_real.country %></option>').val("<%= #creditor1_real.id %>");
$select1.append($option1).trigger('change');
<% elsif params[:action] === "create" && #creditor1 || params[:action] === "new" && #creditor1 %>
var $option1 = $('<option selected><%= #creditor1.name %>, <%= #creditor1.city %>, <%= #creditor1.country %></option>').val("<%= #creditor1.id %>");
$select1.append($option1).trigger('change');
<% else %>
var $option1 = $('<option selected>Search</option>');
$select1.append($option1).trigger('change');
<% end %>
for me, i found solution to just find and plucking model in select options, while keeping the ajax source on js side
<%= f.select :song_creditor_1, Song.where(song_id: song.id).pluck(:song_name, :id), {}, class: 'your-select-2-class' %>
you can select all from your model, but in my case it slowing page load

Knockout-Kendo dropdownlist Ajax observableArray get selected item name

My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.
The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.

Select2 nested json parsing not working Rails3

I'm trying to make select2 working with my ajax loaded json data with nested attributes.
I wanna get something like this http://ivaynberg.github.io/select2/#multi.
eaxmple json:
[{
id: 1,
name: "GroupName",
users: [{id: 1, name: 'UserName'}, {id: 2, name: 'SecondUser}]
}]
On the site they use <optgroup label="GroupName"><option value="1">UserName</opyion></optgroup> and getting the right result.
In my case it displays nesting properly, but I can select only GroupName, but I need to select nested userName and make GrouoName unselectable, only gor informational purposes.
code:
$('#user_tokens').select2({
placeholder: "Search for a user",
minimumInputLength: 0,
tags: true,
multiple: true,
ajax: {
url: "messages/users_data.json",
dataType: 'json',
quietMillis: 100,
data: function(search, page) {
return {
q: search,
per: 3,
page: page
};
},
results: function(data, page) {
return {
results: data,
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop"
});
formatResult:
var formatUserResult = function(data) {
var optgroup = "";
var users = "";
if (data.name !== undefined) {
data.users.forEach(function(e) {
users += "<li class='select2-results-dept-1 select2-result select2-result- selectable'>" +
"<div class='select2-result-label'>" +
"<span class='select2-match'></span>"+
e.firstname +
"</div>" +
"</li>";
});
optgroup += "<div class='select2-result-label'>" +
"<span class='select2-match'></span>" +
data.name + "</div>" +
'<ul class="select2-result-sub">' + users + '</ul>';
}
return optgroup;
}
The problem is that optgroup must have class: 'select2-result-unselectable'
Dunno what to do with it.

Resources