DataTables cannot recognize data from DOM - dom

I have this simple table and the tbody fills with loadLogsTable(); function
<table id="logsTable" style="width:100%;text-align:center;">
<thead>
<th style="width:9%;">Choose</th>
<th style="width:15%;">Ip</th>
<th style="width:15%;">Hostname</th>
<th style="width:50%;">Log</th>
<th style="width:15%;">Date</th>
</thead>
<tbody id="logData"></tbody>
</table>
Here is the loadLogsFunction:
function loadLogsTable()
{
jQuery.ajax({
type: "POST",
async : true,
url: "classes/classesController.php",
data: { method: "getLogsList"},
contentType : ('application/x-www-form-urlencoded'),
dataType : "html" ,
success : function(data){
$("#logData").html(data);
}
});
}
I initialize this table with dataTables but it doesn't paginate them (i have choose 10 rows per page) and it looks like it cannot see table's data. I also cannot search in table's data.
$(document).ready(function()
{
loadLogsTable();
$('#logsTable').dataTable({ // Init pagination
"aoColumnDefs": [{ "bSortable": false, "aTargets": [ 0,1,2,3,4] } ],
"sPaginationType": "full_numbers" ,
"bLengthChange": false,
iDisplayLength": 10
});
});

Issue 1: your iDisplayLength is not properly enclosed by quotes.
You have:
iDisplayLength": 10
but you will avoid an error if instead you have:
"iDisplayLength": 10
That should eliminate your javascript errors.
http://jsfiddle.net/MmDFN/1/
Issue 2: have you examined the ajax data source and server-side processing examples on the datatables site, or looked at mrender? I can't say the way you are using ajax with datatables is conventional.
http://www.datatables.net/examples/
http://www.datatables.net/ref#mrender

mg1075 is right the iDisplayLength was missing a quote.
http://jsfiddle.net/nr5Cw/2/
"<--missing

Related

Using GitHub list-issues-for-a-repository API

When you go to GitHub, under Issues, it pulls up all the open issues as an HTML page. We'd like to implement a dashboard showing all the issues in a repository, grouped by labels, including those issues which are not correctly labelled.
This is the corresponding list-issues-for-a-repository API.
While I was initially using jQuery and Javascript, am now using PHP for a proof-of-concept because its built-in session handling lets me use the same page to login, have GitHub authenticate & callback, and continue. But it doesn't matter to me, any language is okay.
I've managed to get access to the GitHub API via OAUTH2, but when I get the list of repositories via https://api.github.com/orgs/{org}/repos it comes up as an empty array.
Because the /orgs/{org}/repos API returns an empty array, of course the corresponding /repos/{org}/{repo}/issues API will return an error.
Edit: See this followup for a solution! Glad I finally got it working!
It is a rest API. You need to call some endpoints using an Http request.
I don't know what language you are trying to use so I can't give you a good example on how to acheive this.
If you don't know which language to use yet, use postman to create REST API call to the github API.
Let's say you want to retreive the issues of the microsoft's typescript repo, You would need to call this API endpoint :
https://api.github.com/repos/microsoft/typescript/issues
Notice here that i have replace the :owner and :repo value of documentation for the one i'm trying to get.
You can then pass some parameters to the call to filter your data, for example, the API label.
https://api.github.com/repos/microsoft/typescript/issues?labels=API
This will only return issues that are labelled as API.
This is the basics of how to use an API.
You can use jQuery Ajax to access the Github API and add a basic authentication header to authenticate (see here), an example is shown below, this will pull the issues for a given repo and show the first 10 in an alert window.
See the documentation on pulling issues here: https://developer.github.com/v3/issues/ to see which parameters you can use to filter, sort etc.
For example you can get all issues labelled 'bug' using:
/issues?labels=bug
This can include multiple labels, e.g.
/issues?labels=enhancement,nicetohave
You could easily modify to list in a table etc.
const username = 'github_username'; // Set your username here
const password = 'github_password'; // Set your password here
const repoPath = "organization/repo" // Set your Repo path e.g. microsoft/typescript here
$(document).ready(function() {
$.ajax({
url: `https://api.github.com/repos/${repoPath}/issues`,
type: "GET",
crossDomain: true,
// Send basic authentication header.
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
success: function (response) {
console.log("Response:", response);
alert(`${repoPath} issue list (first 10):\n - ` + response.slice(0,10).map(issue => issue.title).join("\n - "))
},
error: function (xhr, status) {
alert("error: " + JSON.stringify(xhr));
}
});
});
Below is a snippet listing issues for a (public) repo using jQuery and the Github API:
(Note we don't add an authentication header here!)
const repoPath = "leachim6/hello-world" //
$(document).ready(function() {
$.ajax({
url: `https://api.github.com/repos/${repoPath}/issues`,
type: "GET",
crossDomain: true,
success: function (response) {
tbody = "";
response.forEach(issue => {
tbody += `<tr><td>${issue.number}</td><td>${issue.title}</td><td>${issue.created_at}</td><td>${issue.state}</td></tr>`;
});
$('#output-element').html(tbody);
},
error: function (xhr, status) {
alert("error: " + JSON.stringify(xhr));
}
});
});
<head>
<meta charset="utf-8">
<title>Issue Example</title>
<link rel="stylesheet" href="css/styles.css?v=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
</head>
<body style="margin:50px;padding:25px">
<h3>Issues in Repo</h3>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Issue #</th>
<th scope="col">Title</th>
<th scope="col">Created</th>
<th scope="col">State</th>
</tr>
</thead>
<tbody id="output-element">
</tbody>
</table>
</body>

ReferenceError: " postIts.forEach(function(postit)" on list.ejs? postIts is not defined at eval (eval at compile

I need to loop through an object PostIts and display the "Id", " Title" with an ejs "forEach" Loop Am using sails.js "1.2.3" and mongodb on local host, but i get error
ReferenceError : postIts is not defined at eval (eval at compile ?
Here is the code on the PostItsController.js:
module.exports = {
list: function(req, res) {
// res.view('list');
PostIts.find({}).exec(function(err, postIts) {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('list', { postIts: postIts });
});
}
};
And here is the code on list.ejs:
<tbody>
<% postIts.forEach(function(postit){ %>
<tr>
<td>
<%= postit.id %>
</td>
<td>
<%= postit.title %>
</td>
<td></td>
</tr>
<% }) %>
</tbody>
I should get the value of the ID and title displayed on the list.ejs page in a table, but instead I get an error that the postIts object is not defined.
First of all your route '/postIts/list': { view: 'list' }, should point to an action (since it has backend logic) not a view, so in your case "/postIts/list": "PostItsController.list", but if you're using actions2 things would be simpler
Secondly you don't need to tell your users that you have a database error error: "Database Error"
Using Actions2
sails generate action post/list
In your config/route.js
'POST /api/v1/post/list': { action: 'post/list' },
In your action
module.exports = {
friendlyName: "List Posts",
description: "List all post in our site",
inputs: {},
exits: {
success: {
description: "The path to your template file",
viewTemplatePath: "list"
}
},
fn: async function(inputs) {
var posts = await Post.find();
// All done.
return { postIts: posts };
}
};
postit works
An Boohoo! it works
https://sailsjs.com/documentation/concepts/actions-and-controllers/routing-to-actions
If you're sure that res.view('list', { postIts: postIts }); is actually sending the correct data you can use _.each(postIts, cb()) ... instead
For some reason the postIts object didnt save the data from the post req I made instead it just recalled what I posted. and I used the '_.each(postIts, function (postit)' and it finally worked.
to me its like a magic happened hahaha but yeah I learned from it.
thanks #Navicstein Rotciv for the quick replies.

test list of dynamically created table headers using protractor and angular 6

I am using protractor with angular 6. stuck in a situation where i want to write test case to test a list of table headers which are created with data coming from backend called in ngOnInit.
i tried using tick and fakeAsync but keep on getting error
Failed: Cannot read property 'assertPresent' of null
below is my code:
app.po.ts
goToScannersList() {
return browser.get('/scanners');
}
getScannersList() {
let items = element.all(by.css('.scannerlist th')).map(function (elm) {
return elm.getText();
});
return items;
}
If i use spec like in 1) i get error mentioned above even if i remove page.goToScannersList();
but if use spec like in 2) my test is success irrespective of what value it returns.
1)
app.e2e-spec.ts
it('should display list of scanners', fakeAsync(() => {
page.goToScannersList();
tick(4000);
expect(page.getScannersList()).toEqual([
"ScannerID",
"Desc",
"Owner"
]);
}));
2)
app.e2e-spec.ts
it('should display list of scanners', () => {
page.goToScannersList();
fakeAsync(()=>{
tick(4000);
expect(page.getScannersList()).toEqual([
"ScannerID",
"Desc",
"Owner"
]);
})
});
scanners.component.html
<table class="scannerlist" id="scannersList" style="text-align:center;width:100%">
<thead>
<tr ><th *ngFor="let col of scannerKeys">{{col}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of scannerData">
<td>{{row.ScannerID}}</td>
<td>{{row.Desc}}</td>
<td>{{row.Owner}}</td>
</tr>
</tbody>
</table>
scanners.component.ts
ngOnInit() {
this.scannerService.getScannerDetails().subscribe((data)=>{
this.scannerData = data.Data;
this.scannerKeys = this.getKeys(data.Data[0]);
});
}
let me know if anybody has any idea how to implement it. thanks in anticipation.

How to fetch data from mongodb in MERN

I got a problem while getting information from db to frontend in MEAN Stack.
i've try using axios plugin to fetch data, but nothing show.
this is the code:
and this is my data in mongodb:
how can i show the information to this part (ex: for username)?
<div className="user-details">
<tr>
<th>Username: </th>
<th></th>
</tr>
</div>
I am not sure about what is your problem exactly is, you set user as an array, but in render method you treat as a "text", try to iterate over each user by using map method and show each individual users information, if you have problem getting information from your API, try to set proxy in client-side package.json, to API port, and use actions in reacts ComponentDidMount lifecycle.
You can use like below, Add header to your axios request, set 'crossDomain': true to overcome cors errorr.
export default class Profile extends Component{
constructor(props){
super(props);
this.state = {
users: []
}
}
conmponentDidMount(){
axios.get('/api/account/profile',{ headers: { 'crossDomain': true, 'Content-Type': 'application/json' } })
.then(res=> {
this.setState({ users: res.data }).then(profileState => {
console.log(JSON.stringify(this.state.users))
}); //It sets the state asynchronously
})
}
render(){
<div>
<div className="user-details">
{
this.state.users.map(user =>
<tr>
<td>Username: </td>
<td>{user.name}</td>
</tr>
)
}
</div>
</div>
}
}
thanks,
actually i just used this.state.user.name without maping to show from database
<strong>Name:</strong>{this.state.user.name}<br/>
and in api i get the user id in url to get current user/active user from session.
axios.get('/api/account/profile/info?id=' +id)
.then(res => {
this.setState({ user: res.data.user });
})

knockoutjs mapping select data-bind options

I am having problems binding the selected value of a selectbox to a property within the view model. For some reason it keeps coming back unchanged when posted back to the server.
My Html is:
<form action="/Task/Create" data-bind="submit: save">
<table border="1">
<tr>
<td>ref type</td>
<td><select data-bind="options: ReferenceTypes, optionsText: 'Name', optionsCaption: 'Select...', value:Task.ReferenceTypeId"></select></td>
<td>Reference</td>
<td><input data-bind="value:Task.Reference" /></td>
</tr>
</table>
<button type="submit">Save Listings</button>
</form>
The Javascript is:
<script type="text/javascript">
var viewModel = {};
$.getJSON('/Task/CreateJson', function (result) {
viewModel = ko.mapping.fromJS(result.Data);
viewModel.save = function () {
var data = ko.toJSON(this);
$.ajax({
url: '/Task/Create',
contentType: 'application/json',
type: "POST",
data: data,
dataType: 'json',
success: function (result) {
ko.mapping.updateFromJS(viewModel, result);
}
});
}
ko.applyBindings(viewModel);
});
</script>
JSON from Fiddler that gets loaded into the page as below.
{
"ContentEncoding":null,
"ContentType":null,
"Data":{
"Task":{
"ReferenceTypeId":0,
"Reference":"Default Value"
},
"ReferenceTypes":[
{
"Id":2,
"Name":"A Ref Type"
},
{
"Id":3,
"Name":"B Ref Type"
},
{
"Id":1,
"Name":"C Ref Type"
}
]
},
"JsonRequestBehavior":1
}
This comes back into the server (ASP.NET MVC3) correctly, with the updated Reference string value, but ReferenceTypeId is not bound to the correctly selected drop down value. Do I need to perform any additional functions to bind correctly etc? Or tell the data-bind what the select value column is (Id) etc? I have checked in Fiddler on the values getting posted back from the browser, and it has the same original value (0). So it is definately not the server.
I hope someone can help, if you need any further information please ask.
Kind Regards
Phil
The issue is that your options binding will try to assign the object that it is bound to, to the value observable specified.
For example if you select "A Ref Type" the options binding will push the json object
{ "Id":2, "Name":"A Ref Type" }
Into your Task.ReferenceTypeId observable which will then be serialized back to your server. In this case you need to add an optionsValue config options to tell the binding just to save the id.
<select data-bind="options: ReferenceTypes, optionsText: 'Name',
optionsCaption: 'Select...', optionsValue: 'Id', value:Task.ReferenceTypeId">
</select>
Here's an example.
http://jsfiddle.net/madcapnmckay/Ba5gx/
Hope this helps.