Datatables data not applyed to table - database

I am making ajax request with data send to method which returns data from database. I do get response (checked under network) but it doesn't get inserted into the table for some reason. Here is my code:
<table class="table table-hover" id="users-table">
<thead>
<tr>
<th>Id</th>
<th>Id_sport</th>
<th>Id_league</th>
<th>Id_user</th>
<th>Points</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
</table>
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
"ajax": {
url: "{!! route('get.leaderboardsData') !!}",
dataSrc: "",
data: { id_sport: "3" }
},
columns: [
{ data: 'id', name: 'id' },
{ data: 'id_sport', name: 'id_sport' },
{ data: 'id_league', name: 'id_league' },
{ data: 'id_user', name: 'id_user' },
{ data: 'points', name: 'points' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
});
</script>
And here is function that return data from database:
public function leaderboardsData(Request $request)
{
$sport_id = $request->get('id_sport');
if($sport_id==="0")
{
$query = DB::table('scores');
return DataTables::of($query)->toJson();
}
else
{
$query = DB::table('scores')->where('id_sport', '=',$sport_id);
return DataTables::of($query)->toJson();
}
}
I am developing in Laravel.

Related

DataTables - Requested unknown parameter on 3 of 7 Columns

I'm at my wits end with this issue and hoping someone can help. I've perused all the other answers and none of the solutions offered are resolving my problem. The following is the JSON string:
{
Description="XT86 EXTENDED WARRANTY (3 YEARS)",
Id=88,
InternalPartNumber="000-063",
ManufacturerPartNumber="000-063",
SellPrice=350.00,
Cost=280.00,
Category="Maintenance"
}
The following is my JS:
$('#products').dataTable({
serverSide: true,
ajax: {
url: "/Product/LoadProducts",
type: "POST",
datatype: "json"
},
columns: [
{ data: "id" },
{ data: "internalpartnumber" },
{ data: "manufacturerpartnumber" },
{ data: "description" },
{ data: "category" },
{ data: "sellprice" },
{ data: "cost" }
]
});
The HTML is as follows:
<div class="shadow-lg p-1 mb-1 bg-secondary rounded">
<table class="table table-hover table-striped table-bordered table-sm w-100" id="products">
<thead class="bg-primary">
<tr style="cursor:pointer;" class="text-light">
<th scope="col">Id</th>
<th scope="col">DCT Part #</th>
<th scope="col">MFG Part #</th>
<th scope="col">Description</th>
<th scope="col">Category</th>
<th scope="col">Sell Price</th>
<th scope="col">Cost</th>
</tr>
</thead>
</table>
</div>
The result is the following:
DataTables warning: table id=products - Requested unknown parameter
'internalpartnumber' for row 0, column 1. For more information about
this error, please see http://datatables.net/tn/4
Clicking OK on the error does load the table but 3 columns are missing data.
I've tried removing { data: "internalpartnumber" } but then I get the error on ManufacturingPartNumber. When I remove { data: "manufacturerpartnumber" } I get the error on SellPrice. When I remove { data: "sellprice" } I get no errors!
When I view the data from Visual Studio, the order the data is in is the same as I have it for each "index" order however when you expand each row index, it is being sorted.
Any help that can be provided would be much appreciated.
The LoadProducts method is as follows:
var results = (from p in _productRepository.GetAllActive
select new
{
p.Id,
p.InternalPartNumber,
p.ManufacturerPartNumber,
p.Description,
Category = p.ProductCategory.Display,
p.SellPrice,
p.Cost
});
Your Columns in your DataTable are not set up in an order as your data is
HTML
<table id="products" class="display" style="width:100%">
<thead>
<tr>
<th>Description</th>
<th>Id</th>
<th>InternalPartNumber</th>
<th>ManufacturerPartNumber</th>
<th>SellPrice</th>
<th>Cost</th>
<th>Category</th>
</tr>
</thead>
</table>
Jquery
var ret = {
data: [
{
Description: "XT86 EXTENDED WARRANTY (3 YEARS)",
Id: 88,
InternalPartNumber: "000-063",
ManufacturerPartNumber: "000-063",
SellPrice: 350.00,
Cost: 280.00,
Category: "Maintenance"
}
]
};
$('#products').dataTable({
data: ret.data,
columns: [
{ data: "Description" },
{ data: "Id" },
{ data: "InternalPartNumber" },
{ data: "ManufacturerPartNumber" },
{ data: "SellPrice" },
{ data: "Cost" },
{ data: "Category" }
]
});
I was finally able to figure this out. In Chrome, I selected the Network Option under the developer tools to examine the payload. What I noticed is that the first letter of the columns was lowercased which was different than what Visual Studio was showing.
I updated my columns definitions to the following:
columns: [
{ data: "id", name: "id", autoWidth: true },
{ data: "internalPartNumber", name: "internalPartNumber", autoWidth: true },
{ data: "manufacturerPartNumber", name: "manufacturerPartNumber", autoWidth: true },
{ data: "description", name: "description", autoWidth: true },
{ data: "category", name: "category", autoWidth: true },
{ data: "sellPrice", render: $.fn.dataTable.render.number(',', '.', 2, '$') },
{ data: 'cost', render: $.fn.dataTable.render.number(',', '.', 2, '$') }
]
and now everything works.

How to push a item to an Angular List? [duplicate]

This question already has answers here:
Arrow Functions and This [duplicate]
(5 answers)
Closed 4 years ago.
first of all thank you for taking the time to read this and possibly to help me.
I created a list and I want to add a item to it that I am getting from a AJAX call to an MVC Controller
Typescript:
export class FunctionalityComponent {
public items = [{ Name: "Name", Nachname: "Nachname" },
{ Name: "Name", Nachname: "Nachname" },
{ Name: "Name", Nachname: "Nachname" }];
}
addRowMVC() {
$.ajax({
url: '/Functionality/AddRow',
type: 'post',
success: function (data) {
this.items.push({Name: data.name, Nachname: data.nachname});
},
error: function () {
alert("error");
}
});
}
MVC-Controller:
class Normal
{
public string Name;
public string Nachname;
public Normal(string name, string nachname)
{
Name = name;
Nachname = nachname;
}
}
public JsonResult AddRow()
{
var a = new Normal("aa", "bb" );
return Json(a);
}
View:
<button (click)="addRowMVC()" class="btn btn-success">Add Row via MVC</button>
<table>
<thead>
<tr>
<th *ngFor="let head of items[0] | keys">{{head}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items">
<td *ngFor="let list of item | keys">{{item[list]}}</td>
</tr>
</tbody>
</table>
This is probably a bad attempt to get it to work and that's why I'm asking for your guys help. If I try my code it gives me the error that this.items is undefined.
Hope you guys can help me.
Greetings Nico aka. Myridor
Try this solution
export class FunctionalityComponent {
public items = [{ Name: "Name", Nachname: "Nachname" },
{ Name: "Name", Nachname: "Nachname" },
{ Name: "Name", Nachname: "Nachname" }];
}
addRowMVC() {
let state = this;
$.ajax({
url: '/Functionality/AddRow',
type: 'post',
success: function (data) {
state.items.push({Name: data.name, Nachname: data.nachname});
},
error: function () {
alert("error");
}
});
}
Try this solution:
export class FunctionalityComponent {
public items = [{ Name: "Name", Nachname: "Nachname" },
{ Name: "Name", Nachname: "Nachname" },
{ Name: "Name", Nachname: "Nachname" }];
}
addRowMVC() {
let that = this;
$.ajax({
url: '/Functionality/AddRow',
type: 'post',
success: function (data) {
that.items.push({Name: data.name, Nachname: data.nachname});
},
error: function () {
alert("error");
}
});
}

Selected value is not displayed in async mode

I've got a react-select that I'm populating asyncly. The items display just fine however, after an item is selected the list reverts to Loading..., the spinner starts spinning and nothing appears in the select box.
I can only guess the selected value is not being persisted?? not sure. Complete=true in autocompleteLoad() has no affect. Setting isLoading=false has no affect. Here's the code...
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import * as models from '../models'
import Select from 'react-select'
import 'react-select/dist/react-select.css'
interface MovieActorState {
actor: models.Actor[]
loading: boolean
activeMovieId: number
activeActorId: number
acLoading: boolean,
acLabel?: string
}
const data = [{ value: 1, label: 'Mr Holland\'s Opus' },
{ value: 2, label: 'Braveheart' },
{ value: 3, label: 'Batman Forever' },
{ value: 1004, label: 'Star Wars' },
{ value: 1005, label: 'Goonies' },
{ value: 1006, label: 'ET' }];
const actors = [{ Id: 1, Name: 'Mel Gibson', Gender: 'Male', Age: 54, Picture: null },
{ Id: 2, Name: 'Val Kilmar', Gender: 'Male', Age: 49, Picture: null },
{ Id: 3, Name: 'Micheal Keaton', Gender: 'Male', Age: 60, Picture: null },
{ Id: 1002, Name: 'Diane Keaton', Gender: 'Female', Age: 49, Picture: null },
{ Id: 1003, Name: 'Tom Cruise', Gender: 'Male', Age: 55, Picture: null },
{ Id: 1006, Name: 'Richard Simmons', Gender: 'Male', Age: 59, Picture: null }];
const movieactors = [{ MovieId: 1, ActorId: 1 },
{ MovieId: 1, ActorId: 2 },
{ MovieId: 1, ActorId: 3 }];
export class Test extends React.Component<RouteComponentProps<{}>, MovieActorState> {
constructor(props) {
super(props);
this.that = this;
this.state = {
actor: [],
loading: true,
activeMovieId: 0,
activeActorId: 0,
acLoading: false
};
console.log('movieactor.fetch()', this.state)
this.setState({
actor: actors,
loading: false,
});
}
that;
public render() {
console.log('movieactor.render', this.state)
let contents = this.state.loading
? <p><em>Loading...</em></p>
: this.renderTable(this.state.actor, true);
return <div>
<h1>MovieActor</h1>
<label>Movie</label>
<Select.Async
name="form-field-name"
loadOptions={this.autocompleteLoad}
valueKey="value"
labelKey="label"
onChange={this.autocompleteSelect.bind(this)}
placeholder="Type to search"
value={this.state.activeMovieId + ''}
isLoading={false}
onClose={this.autocompleteClose.bind(this)}
/><br />
{contents}
</div>;
}
autocompleteSelect(e) {
console.log('movieactor.autocompleteSelect()', e, this.state)
this.setState({
actor: actors.filter((actor) => {
return (actor.Id > e.value);
}),
loading: false,
activeMovieId: e.value,
acLoading: false,
acLabel: e.label
});
}
autocompleteClose(e) {
console.log('movieactor.autocompleteClose()', e, this.state)
this.setState({ acLoading: false });
}
autocompleteLoad(input, callback) {
console.log('autocompleteLoad(' + input + ')')
if (input == null || input.length == 0) {
console.log('null')
callback(null, { complete: true })
return;
}
callback(null, {
options: data, complete: true
})
};
private renderTable(actor: models.Actor[], allowSort: boolean = false) {
let headings = this.renderTableHeadings(allowSort)
return <table className='table'>
<thead>
{headings}
</thead>
<tbody>
{actor.map(item =>
<tr key={item.Id}>
<td>
</td>
<td>{item.Id}</td>
<td>{item.Name}</td>
<td>{item.Gender}</td>
<td>{item.Age}</td>
<td>{item.Picture}</td>
</tr>
)}
</tbody>
</table>;
}
private renderTableHeadings(allowSort: boolean) {
return <tr>
<th></th>
<th>Id</th>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Picture</th>
</tr>
}
}
Update: In my on-going effort to get this to work, it seems the hidden input with the value is missing. According to the react-select docs:
..but when I inspect the dom (after selecting item) it's not there...
I'm going to give this another day, before I replace the component with something else.
Code is working 100% fine,
Please check the WORKING DEMO , there might be some other code that would be affecting issue.

Adding conditional value to angular ng-table

I want to add glyphicon to a column based on row value in ng-table component .For example if row.firstProperty==row.secondProperty then the glyph be added to column.I know how to do this in angular Grid UI but although I review documentations and examples but ‍‍‍‍‍‍I did not find any way in ng-Table.Can anyone suggest a solution to my issue?
Edit:My scenario is that I have a custom directive that it is used to produce many pages with same style and functionality by getting page data and in part of it ng-table is used by defining template for my directive.
ng-table.html
<table ng-table="to.tableParams" class="table" show-filter="{{::to.showFilter}}">
<tr ng-show="to.showHeaders">
<th class="th-select" ng-repeat="column in to.columns">{{column.title}}</th>
</tr>
<tr ng-repeat="row in $data">
<td ng-repeat="column in to.columns" ng-show="column.visible" sortable="column.field" ng-click="save(row)">
{{row[column.field][column.subfield] || row[column.field]}}
<span compile="column.getValue()" ></span>
</td>
</tr>
ngTable Columns is defined in Controllers and one of the columns is html values like glyphicons and buttons that is maked base on object named actionList which is defined in each controller like below:
vm.actionList = [
{
name: 'edit',
body: function (row) {
$state.go("editrule", {ruleId: row.id});
},
glyph: 'glyphicon-pencil',
permission: $scope.permission.edit,
showCondition:"true"
},
{
name: 'view',
body: function (row) {
$state.go("showrule", {ruleId: row.id});
},
glyph: "glyphicon-eye-open",
permission: $scope.permission.watch,
showCondition:"row.modifiedDate==row.createDate"
},
{
name: 'history',
body: function (row) {
$state.go("rulehistory", {ruleId: row.id});
},
glyph: "glyphicon-info-sign",
showCondition: "row.modifiedDate!=row.createDate",
permission: $scope.permission.history
}
];
.I put the logic for creating html column to my directive to prevent repeated code from controllers and delivering it to controllers and the controller part for defining columns is as below :
vm.columns = [
{
title: $translate.instant('URL'),
translate: "URL",
field: 'url',
visible: true,
alignment: 'text-align-lg-left'
},
{
title: $translate.instant('MATCH_TYPE'),
translate: "MATCH_TYPE",
field: 'matchType',
visible: true,
alignment: 'text-align-lg-center',
filter: [{lowercase: []}]
},
{title: $translate.instant('PRIORITY'), translate: "PRIORITY", field: 'priority', visible: true,alignment: 'text-align-lg-center'},
{title: $translate.instant('SOURCE'), tanslate: "SOURCE", field: 'source', visible: true,alignment: 'text-align-lg-center'},
{title: $translate.instant('CATEGORY'), translate: "CATEGORY", field: 'category', visible: true,alignment: 'text-align-lg-center'},
{
title: $translate.instant('CREATE_DATE'),
translate: "CREATE_DATE",
field: 'createdDate',
visible: true,
alignment: 'text-align-lg-center'
},
{
title: $translate.instant('LAST_CHANGE'),
translate: "LAST_CHANGE",
field: 'modifiedDate',
visible: true,
alignment: 'text-align-lg-center'
},
{title: $translate.instant('ACTION') ,translate: "ACTION", field: 'action', visible: true,alignment: 'text-align-lg-center'},
{title: '', visible: true, getValue: htmlValue, id: "actionList"}/*actions*/
];
function htmlValue() {
return $sce.trustAsHtml(actions);
}
The action value comes from directive that contains htmls.The Directive part is as below :
scope.html = function htmlValue() {
var html = "";
/*intentionaly angular ng-repeat not used*/
for (var i = 0; i < scope.actionList.length; i++) {
scope.entry = scope.actionList[i];
scope.permission = scope.entry.permission;
scope.myglyph = scope.entry.glyph;
if (typeof scope.entry.permission == 'undefined' || scope.entry.permission == true) {
debugger
html = '<button ng-show="{{entry.condition}}" type="button" class="btn btn-list" ng-click=' + $interpolate("{{entry.name}}(row)")(scope) + '> ' +
'<span class=\"glyphicon ' + $interpolate("{{entry.glyph}}")(scope) + '\"></span>' +
'</button>' + html;
console.log("this is test");
console.log(scope.test);
}
}
}
scope.$watch('refreshDataFilter', function (newValue, oldValue) {
/*EXTRACT ACTIONS*/
for (var i = 0; i < scope.actionList.length; i++) {
var entry = scope.actionList[i];
Object.defineProperty(scope, entry.name, {value: entry.body});
Object.defineProperty(scope, entry.showCondition, {value: "aaa"});
}
/*define table data filler*/
if (newValue == true) {
renderTable();
scope.refreshDataFilter = false;
}
});
The main problem is here that if I interpolate the values of entry.showCondition I always get the value of of last item in actionList. Is there any solution that I can make html part of table base on conditions?

ng-table data not showing

here my question:
I am trying to build a directive in angular, which would use an ng-table inside. I am using mocked data. The problem is that I cannot render data in the table. here is my directive:
;(function(app) {
app.directive('customTables', [
'NgTableParams',
function(NgTableParams) {
return {
restrict: 'E',
templateUrl: 'templates/directives/table_directive.html',
scope: {
},
link: function(scope) {
var dataset = [{
name: "Moroni50",
age: "50"
}, {
name: "Moroni49",
age: "49"
}];
scope.tableParams = new NgTableParams({}, {
data: dataset
});
}
};
}]);
})(app);
here is the html:
<table ng-table="tableParams" class="table table-bordered table-striped table-condensed">
<tr ng-repeat="user in $data">
<td title="'Name'" filter="{ name: 'text'}" sortable="'name'">{{user.name}}</td>
<td title="'Age'" filter="{ age: 'number'}" sortable="'age'">{{user.age}}</td>
</tr>
here is how I call it:
<custom-table></custom-table>
Any suggestions?
Replace
scope.tableParams = new NgTableParams({}, {
data: dataset
});
with
scope.tableParams = new NgTableParams({}, {
scope.data: dataset
});
and in html:
<tr ng-repeat="user in $data">
with
<tr ng-repeat="user in data">
Try this:
scope.data = [{
name: "Moroni50",
age: "50"
}, {
name: "Moroni49",
age: "49"
}];
scope.tableParams = new NgTableParams({}, {
data: scope.data
});
Try this instead
scope.tableParams = new NgTableParams({}, {
dataset: dataset
});

Resources