Ng-table not calling get data - javascript

I've got implemented ng-table with an ajax call but never call the function from getdata, the function onBuscarTable is never call, I've look at the debbugger console to check it and dosen't call it:
what i'm doing whrong?
here's the js:
$scope.onBuscarTable = function ($defer, params) {
$.ajax({
type: 'GET',
url: '/Home/GetEfficiencyDetails',
cache: false,
contentType: 'application/json; charset=utf-8',
//data: JSON.stringify({ title: "fghfdhgfdgfd" }),
success: function (data) {
$scope.items = data;
$defer.resolve(data);
}
});
};
//$scope.getEffiencyDetails();
$scope.tableBuscar = new ngTableParams({
page: 1, // show first page
count: $scope.items.length, // hides pager
sorting: {
name: 'asc' // initial sorting
}
}, {
counts: [], // hides page sizes
getData: $scope.onBuscarTable
});
$scope.tableBuscar.reload();
and here is the html:
<table ng-table="tableBuscar" show-filter="true" class="table table-striped table-bordered table-condensed table-hover">
<tbody>
<tr>
<th colspan="5">Battery Life</th>
<th colspan="4">SBC</th>
<th colspan="3">ZBC</th>
<th>Overall</th>
</tr>
<tr>
<th>Pool #</th>
<th>True Cap.</th>
<th>Util.</th>
<th>Load Sharing</th>
</tr>
<tr ng-repeat="item in items">
<td>{{item.PoolName}}</td>
<td>{{item.AvgTrueCapacity}}</td>
<td>{{item.AvgEnergyUsageDaily}}</td>
</tr>
</tbody>
</table>

You code should using $http instead of $.ajax
$scope.items = [];
$scope.onBuscarTable = function($defer, params) {
$http.get('/Home/GetEfficiencyDetails').success(function(data) {
$scope.items = data;
$defer.resolve(data);
});
};
//$scope.getEffiencyDetails();
$scope.tableBuscar = new ngTableParams({
page: 1, // show first page
count: $scope.items.length, // hides pager
sorting: {
name: 'asc' // initial sorting
}
}, {
counts: [], // hides page sizes
getData: $scope.onBuscarTable
});
$scope.tableBuscar.reload();

Related

DataTables Requested unknown parameter 'PageId'

I am running into the following error trying to load DataTables Objects data (https://datatables.net/manual/data/):
DataTables warning: table id=report-table - Requested unknown parameter 'PageId' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/
Below is example json data I am recieving from my C# SchemaReport/GetReportJson controller and being used in JQuery ajax success callback to initialize my DataTables:
[{"PageId":"foo","SchemaName":"foo","Name":"foo","LastModified":"foo","LastModifiedUser":"foo"}]
DataTables HTML:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
JQuery ajax and DataTables init script:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
data: data,
columns : [
{
data : 'PageId'
},
{
data : 'SchemaName'
},
{
data : 'Name'
},
{
data : 'LastModified'
},
{
data : 'LastModifiedUser'
}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'csv',
text: 'Download CSV',
filename: 'report-file'
},
{
extend: 'excel',
text: 'Download Excel',
filename: 'report-file',
title: ''
},
]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
I noticed that after acknowledging the error DataTables loads as following and stating 134 entries:
134 matches the character count of the json data (provided in answer). For some reason it appears DataTables is not seeing the json object and parsing individual characters? Just not sure why it would be doing this?
Your columns block should be:
columns : [
{
'data' : 'PageId'
},
{
'data' : 'SchemaName'
},
{
'data' : 'Name'
},
{
'data' : 'LastModified'
},
{
'data' : 'LastModifiedUser'
}
],
You should also be sending your data from the Controller like this:
return Json(schemaData);
You do not need to serialize your data when you are returning a JSON since this will already return data in JSON format and if you use JsonConvert.SerializeObject then you are converting it twice which the DataTable plugin does not like.

How can I give Ajax data (list) to mustache?

I want to put the user object I received as Ajax into {{#user}} in mustache and render it on the screen.
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>user number</th>
</tr>
</thead>
<tbody id="tbody">
{{#users}}
<tr>
<td>{{id}}</td>
</tr>
{{/users}}
</tbody>
</table>
this is conroller
#PostMapping("/api/v1/eduPosts/registerAdminToUser")
public List<User> registerAdminToUser(#RequestBody UserRegisterRequestDto userRegisterRequestDto){
List<User> users=userService.registerAdminToUser(userRegisterRequestDto);
System.out.println(users);
return users;
}
this is index.js
update : function () {
var data = {
adminId: $('#adminId').val(),
userId: $('#userId').val()
};
//var id = $('#id').val();
$.ajax({
type: 'POST',
url: '/api/v1/eduPosts/registerAdminToUser',
dataType: 'json',
contentType:'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(data) {
$.each(data, function(idx, val) {
alert(idx + " " + val.id);
console.log(idx + " " + val.id)
});
alert(JSON.stringify(data))
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
Should I change the js file? Or do I have to change the mustache template?
If I print out the user object in the index.js file, the data is being rendered properly.
Thanks!

JQuery Datatable Reload From Server MVC

I have a Datatable of JQuery generated at first-page load. I am trying to refresh it according to the selected criteria from the selectlist.
My Datatable initialized first like the following code.
<table class="table table-striped table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Select All <input type="checkbox" class="checkbox" id="chkBoxAll"></th>
#foreach (System.Data.DataColumn col in Model.DataTypesTable.Columns)
{
<th> #col.Caption</th>
}
</tr>
</thead>
<tbody>
#foreach (System.Data.DataRow row in Model.DataTypesTable.Rows)
{
<tr>
<td> <input type="checkbox" class="checkbox" name="chkBox" value="#row.ItemArray[0]"></td>
#foreach (var cell in row.ItemArray)
{
<td>
#cell.ToString()
</td>
}
</tr>
}
</tbody>
</table>
<script>
$(document).ready(function() {
$('#dataTable').DataTable();
});
</script>
It initializes well at first. However, when I try to reload it on the selectlistchange event, it doesn't reload anything and displays an error like this.
DataTables warning: table id=dataTable - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'html',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
console.log(result);
$("#dataTable").DataTable({
destroy: true,
data: result,
columns: [
{ data: "Id", name: "Id" },
{ data: "Data Name", name: "Data Name" },
{ data: "Description", name: "Description" },
{ data: "Device Type", name: "Device Type" }
], columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Controller:
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
var json = this.Json(new { data = dt }/*, _jsonSetting*/);
return json;
}
My data is like below from the developer tools:
Please help me out to resolve the issue... Thanks in advance.
After long tries and losing hairs.. I have found a solution clear and add the rows again instead of destroy command. Here is the solution below.
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'json',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
var dataTable = $("#dataTable").DataTable();
dataTable.clear().draw();
$.each(result, function myfunc (index, value) {
// use data table row.add, then .draw for table refresh
dataTable.row.add([
'<input type="checkbox" class="checkbox" name="chkBox" value="' + value.Id + '">',
value.Id,
value.DataName,
value.Description,
value.DeviceType
]).draw();
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Also, it is important to return a json object from the controller action.
PS. If the Json Object has an initial tag like data, you may need to change the looping value.Id to value.data.Id. But it is better to not use any tag.
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
var json = this.Json(dt , _jsonSetting);
return json;
}

Foreach Data not reflected to UI with Knouckout Js Object Obserable

Below is the view modal where I am getting the ajax response and load to the obserable value.
var userManagementVM = {
responseSetUpData: ko.observable({
userList: ko.observable(),
userListViewModel: ko.observableArray(),
MeetingId: ko.observable(),
MeetingTypeId: ko.observable(),
MeetingType: ko.observable()
}),
SetListOfUserInRoles: function () {
var self = this;
var ajaxUrl = ApplicationRootUrl("UserRoleManagement", "UserManagement");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: ajaxUrl,
dataType: "json",
success: function (data) {
self.responseSetUpData(data);
console.log(self.responseSetUpData())
},
error: function (err) {
}
});
}
}
$(document).ready(function () {
ko.applyBindings(userManagementVM, document.getElementById("rightdash-container"));
userManagementVM.SetListOfUserInRoles();
});
The response from the ajax is successfully loaded to the obserable value. Below is the output of the console
HTML code
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Users</th>
<th scope="col">Role</th>
</tr>
</thead>
<tbody data-bind="foreach: responseSetUpData.userListViewModel">
<tr>
<td><input class="form-check-input" type="checkbox" data-bind="checked: SelectedUser"><span data-bind="text: $data.FirstName"></span></td>
<td><select data-bind="options: $data.Roles,optionsText: 'Name',value: $data.SelectedRoleId,optionsCaption: '-- Select Role --'"></select></td>
</tr>
</tbody>
</table>
The value is not bind to the UI.
You need to get the value of the observable - responseSetUpData() in the binding:
<tbody data-bind="foreach: responseSetUpData().userListViewModel">
Otherwise you are trying to get userListViewModel from the observable function object :-)

bootstrap onDblClickRow event not working on mobile device

I have bootstrap table and it has function on double click event. On my laptop it works fine, however on the mobile when I try double tap row nothing happens.
CODE:
<div class="col-xs-24 main">
<table id="table-pagination" class="table table-striped">
<thead>
<tr>
<th data-field="order_create_date" data-align="center"> Užsakymo data</th>
<th data-field="order_user_id" data-align="center"> Vartotojas</th>
<th data-field="order_client_name" data-align="center">Užsakovas</th>
<th data-field="order_client_order_number" data-align="center">Užsakovo užsakymo nr</th>
<th data-field="order_pickup_date" data-align="center">Pasikrovimo data</th>
</tr>
</thead>
</table>
<script>
getorders(function(r) {
$('#table-pagination').bootstrapTable({
data: r,
pagination: true,
pageList: [10, 20, 50, 100],
search: true,
showColumns: true,
onDblClickRow: function (row, $element) {
var key = row["key"];
window.location.href = "orders/display/"+key;
}
});
});
</script>
</div>
</div>
getorders is a callback function used to get table data using ajax request
CODE:
function getorders(callback) {
var data = {};
$.ajax({
url: "home/get_orders",
type: "POST",
data: "",
dataType: "html",
success: function(response) {
var jsonarray = $.parseJSON(response);
callback(jsonarray);
}
});
}
Like I said on desktops and laptops works fine, not sure about tables but on mobiles (androids) not working.
Maybe its window.location.href = "orders/display/"+key; not working on mobiles. I have tried adding return false below it didn't helped.
Any suggestions?

Categories