This function
public function groups_priviledges($user_id = NULL){
$data['groups'] = $this->priviledges_model->admin_groups();
$data['member'] = $this->priviledges_model->empAdminGroup($user_id);
echo json_encode($data);
}
has returned this json array on my browser
{
"groups": [
{
"id": "1",
"description": "Human Resources",
"added": "2018-06-21 16:27:20",
"status": "1"
},
{
"id": "2",
"description": "Purchasing",
"added": "2018-06-21 16:31:47",
"status": "1"
},
{
"id": "4",
"description": "Warehouse",
"added": "2018-06-21 16:31:47",
"status": "1"
}
],
"member": [
{
"id": "41",
"admin_group_id": "4",
"employee_id": "16"
}
]
}
I am having a serious challenge using ajax to list all the groups, and a checkbox checked only if a member belongs to a particular group.
My html currently looks likr this
<table class="table table-striped">
<thead>
<tr>
<th> Priviledge </th>
<th> Options </th>
</tr>
</thead>
<tbody id="priviledges"></tbody>
</table>
And my ajax... I'm so lost here, doesn't return anything
<script>
$(function(){
priviledges();
function priviledges(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>users/groups_priviledges/<?php echo $tuser['employeeId'] ?>',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var groups;
for(groups=0; groups<data.length; i++){
html += '<tr>'+
'<td>'+data[groups].description+'</td>'+
'<td>'+'<label class="check"><input type="checkbox" name="group[]" class="icheckbox" checked=""/>'+
'</tr>';
}
$('#priviledges').html(html);
},error: function(){
alert('Could not retrieve data');
}
});
}
});
Thanks all in anticipation.
Your problem is that data is an object which contains an array (stored within the "groups" property of the object). However when you write data.length and data[groups] you're treating data itself as if it were the array, which it isn't.
The solution is to refer to the groups property of the data object and then refer to a specific array item within that:
var data = {
"groups": [{
"id": "1",
"description": "Human Resources",
"added": "2018-06-21 16:27:20",
"status": "1"
},
{
"id": "2",
"description": "Purchasing",
"added": "2018-06-21 16:31:47",
"status": "1"
},
{
"id": "4",
"description": "Warehouse",
"added": "2018-06-21 16:31:47",
"status": "1"
}
],
"member": {
"id": "41",
"admin_group_ids": ["1", "4"],
"employee_id": "16"
}
};
var html = '';
for (var count = 0; count < data.groups.length; count++) {
html += '<tr>' +
'<td>' + data.groups[count].description + '</td>' +
'<td>' + '<label class="check"><input type="checkbox" name="group[]" class="icheckbox"';
for (var ids = 0; ids < data.member.admin_group_ids.length; ids++) {
if (data.member.admin_group_ids[ids] == data.groups[count].id) {
html += "checked=checked";
break;
}
}
html += '/></tr>';
}
$('#privileges').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th> Privilege </th>
<th> Options </th>
</tr>
</thead>
<tbody id="privileges"></tbody>
</table>
N.B. In the above I have also:
corrected the spelling of "privilege"
corrected the error in the definition of the for loop (i was not defined)
changed the loop variable name to "count", so it's not confused with the "groups" property in the data.
assumed that the JSON structure of "member" will now be changed to make sense when the member is in more than one admin group, and will be like this: "member": { "id": "41", "admin_group_ids": ["1", "4"], "employee_id": "16" } (see comments below)
Related
I have problem when i want to get a value from json
const data = {
"first_name": "Sammy",
"last_name": "Shark",
"location": "Ocean",
"websites": [{
"description": "work",
"URL": "https://www.digitalocean.com/"
}, {
"desciption": "tutorials",
"URL": "https://www.digitalocean.com/community/tutorials"
}],
"social_media": [{
"description": "twitter",
"link": "https://twitter.com/digitalocean"
}, {
"description": "facebook",
"link": "https://www.facebook.com/DigitalOceanCloudHosting"
}, {
"description": "github",
"link": "https://github.com/digitalocean"
}]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var dataTarget = "https://tech/json-data.php";
$.getJSON(dataTarget, function(data) {
var output;
output += `<tr>
<th scope="col">name</th>
<th scope="col">description</th>
<tbody>`
$.each(data, function(key, val) {
output += '<tr>';
output += '<td>' + val.websites.description + '<td>';
output += '</tr>';
output += '</tbody>';
});
$('table').html(output);
});
</script>
but it showing an error code "Uncaught TypeError: Cannot read property 'description' of undefined"
if you only need websites decription, use data.websites for $.each() parameter, because from data you need second loop/each
var data = {
"first_name": "Sammy",
"last_name": "Shark",
"location": "Ocean",
"websites": [{
"description": "work",
"URL": "https://www.digitalocean.com/"
},
{
"description": "tutorials",
"URL": "https://www.digitalocean.com/community/tutorials"
}
],
"social_media": [{
"description": "twitter",
"link": "https://twitter.com/digitalocean"
},
{
"description": "facebook",
"link": "https://www.facebook.com/DigitalOceanCloudHosting"
},
{
"description": "github",
"link": "https://github.com/digitalocean"
}
]
}
var output = ''
$.each(data.websites, function(key, val) {
output += '<tr><td>' + val.description + '</td></tr>';
});
//console.log(output)
$('table').html(output);
<table></table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It is throwing an error because the "websites" key is an array, instead you should access the array element by referring to it's index number like this:
output += "<td>" + val.websites[0].description + "<td>";
With push of a button there should be a html that contains info from json, but nothing happens.
When i used console.log to show the whole JSON info, it worked. BUt when added table and and only specific arrays, it does nothing. There are no errors.
<button type="button" id="nappi">paina</button>
<table id="taulu">
<tr>
<th>manufacturer</th>
<th>model</th>
<th>price</th>
<th>wiki</th>
</tr>
</table>
var nappi = document.getElementById("nappi");
nappi.addEventListener("click", function(){
$(document).ready(function(){
$.getJSON("./cars.json", function(data){
var tiedot = '';
$.each(data, function(key, value){
tiedot += '<tr>';
tiedot += '<td>'+value.manufacturer+'</td>';
tiedot += '<td>'+value.model+'</td>';
tiedot += '<td>'+value.price+'</td>';
tiedot += '<td>'+value.wiki+'</td>';
tiedot += '</tr>';
});
$('taulu').append(tiedot);
});
});
});
{
"data": [{
"manufacturer": "Porsche",
"model": "911",
"price": 135000,
"quality": [{
"name": "overall",
"rating": 3
}, {
"name": "mechanical",
"rating": 4
}, {
"name": "powertrain",
"rating": 2
}, {
"name": "body",
"rating": 4
}, {
"name": "interior",
"rating": 3
}, {
"name": "accessories",
"rating": 2
}],
"wiki": "http://en.wikipedia.org/wiki/Porsche_997"
}]
}
You forgot # before the ID. $(' > # < taulu ') $('#taulu')
I want to output two tables, each sourcing information from two separate arrays within the same JSON source, but for some reason my code doesn't work.
JSON Message:
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
HTML Code:
<table id="policies-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Score</th>
</tr>
</thead>
</table>
<table id="services-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Score</th>
</tr>
</thead>
</table>
JavaScript Code:
var the_url = "www.example.com"
var columnsDef = [
{ data : "name" },
{ data : "id" },
{ data : "score" }
];
$(document).ready(function() {
$('#policies-table').DataTable({
ajax : {
url : the_url,
dataSrc: "Policies"
},
columns : columnsDef
}),
$('#services-table').DataTable({
ajax : {
url : the_url,
dataSrc: "Services"
},
columns : columnsDef
})
});
You are not iterating through your JSON variable. As prabodhprakash suggested, writing "Policies" and "Services" won't help either.
I suggest you to take a look at this fiddle
You can initialize multiple datatables with the same syntax that you use for initializing a single one:
var json = {
"Policies": [{
"name": "A",
"id": "1",
"score": "0"
}],
"Services": [{
"name": "B",
"id": "2",
"score": "0"
}]
}
var policyTable = $("#policies-table").DataTable({
"data" : (json.Policies),
"columns": [
{ "data": "name" },
{ "data": "id" },
{ "data": "score" }]
});
var serviceTable = $("#services-table").DataTable({
"data" :(json.Services),
"columns": [
{ "data": "name" },
{ "data": "id" },
{ "data": "score" }]
});
I am trying to convert data present in an HTML table into JSON link. I'm getting undefined values in object.
HTML code:
<table colspan="2" border="1">
<tr>
<th>Source</th>
<th>Destination</th
</tr>
<tr ng-repeat="col in MapCol">
<td>
<select ng-model="col.value" ng-init="col.value=MainData.headers[$index].header">
<option ng-selected="{{head.header == col.value}}" ng-repeat="head in MainData.headers">{{head.header}}
</option>
</select>
</td>
<td>{{col.ColName}}</td>
</tr>
</table>
<br/>
<button ng-click="map();">Map</button>
Controller code:
var app = angular.module("ShrTest", []);
app.controller("Test1", function ($scope) {
$scope.MainData = { "name": "1-06082015185338.txt", "headers": [{ "header": "Name" }, { "header": "Age" }, { "header": "Address" }], "records": [{ "Name": "Paul", "Age": "23", "Address": "1115 W Franklin" }, { "Name": "Bessy the Cow", "Age": "5", "Address": "Big Farm Way" }, { "Name": "Zeke", "Age": "45", "Address": "W Main St" }] };
$scope.MapCol = [{ "ColName": "Col1" }, { "ColName": "Col2" }, { "ColName": "Col3" }];
$scope.map=function(){
$scope.fields=[{"source":$scope.value,"destination":$scope.ColName}];
console.log(" $scope.fields..", $scope.fields);
}
});
JS
$scope.map=function(){
$scope.fields = [];
for(i in $scope.MapCol){
var obj = $scope.MapCol[i]; $scope.fields.push({"source":obj.value,"destination":obj.ColName})
}
console.log($scope.fields);
}
Here is Modified fiddle:
Demo Here
I hope this will help you.
I am using the TreeTable plugin:
http://ludo.cubicphuse.nl/jquery-treetable/#examples
<table id="example-basic">
<thead>
<tr>
<th>Name</th> <th>Status</th> <th>id</th>
</tr>
</thead>
<tbody data-bind="foreach: TreeView">
<tr data-bind="attr: { 'data-tt-id': id ,'data-tt-parent-id': Parentid}">
<td data-bind="text: Name"></td>
<td data-bind="text: Status"></td>
<td data-bind="text: id"></td>
</tr>
</tbody>
</table>
<button type="button" name="test" onclick="test()"></button>
The below works if I HardCode as is and the result is shown as a nicely formatted TreeView.
ko.applyBindings({ TreeView: [{ "id": "1", "Parentid": null, "Name": "test1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "test2", "Status": "OK" }] }
But, I am getting the value from the server(put the value obtained from server in "str" variable) and doing the binding as below:
str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]',
json = JSON.stringify(eval("(" + str + ")")),
ko.applyBindings({ TreeView: json})
function reload() {
//ko.applyBindings({ TreeView: {} });
str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }]'
json = JSON.parse(str),
ko.applyBindings({ TreeView: json})
I get the following error:
Error: Unable to parse bindings.
Message: ReferenceError: 'id' is undefined;
Bindings value: attr: { 'data-tt-id': id ,'data-tt-parent-id': Parentid}
Can someone please help. Thanks!
The Json object returned had to be converted to type string and then parsed. This resolved the above issue
New Issue:
I was just playing around with the treetable plugin. I wish to reload the data from server on button click(or ajax call every 5 sec). The data is duplicated.
You are stringifying the JSON instead of parsing it, and using eval() when you don't need it. Instead, just use JSON.parse().
var str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]';
var json = JSON.parse(str);
ko.applyBindings({ TreeView: json });