How to display json array coming from url through ajax in angularjs - javascript

I have a json array coming from a url:
http://blahblahblah.com/company/all, like this:
in angularjs controller, i have something like this:
$('#example-1').DataTable({
"ajax" : 'http://blahblahblah.com/company/all',
"columns": [
{"data": "companyId"},
{.....}, // I can't assign "data" name to array because it is already unnamed.
]
});
Traversing in html table_id example-1
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</tfoot>
Output:
So, my question is how do I identify the column names from above UNNAMED JSON ARRAY mentioned on top of the question, and display it in html table. Waiting for your kind response.
I am thinking to do something like this

$(document).ready(function() {
$('#example').DataTable( {
"ajax": "http://blahblahblah.com/company/all",
"columns": [
{ "data": "companyId" },
{ "data": "legalName" },
{ "data": "dbaName" },
{ "data": "formation"}
]
} );
} );
you need to add more information to the datatable while intializing what are the keys to be shown. form more details check datatable objects

I was unable to identify the correct syntax of identifying and using the column names in my JSON array, which I did like this, and solved my problem. So now the data is displayed fine in my table, this way:
$.getJSON('http://blahblahblah/company/all', function(data) {
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId"},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I also added hyperlink to companyId like this:
$.getJSON('http://blahblahblah/company/all', function(data) {
var companyId = null;
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId", "render": function(data, type, row, meta) {
if( type==='display' ) {
companyId = data;
data = '' + data + '';
}
return data;
}},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I am thankful to all of you for helping me grab the track.
Thanks.

Actual way to do this is to use ng-repeat in the data array. And for the data fetch, use an angular service with a promise.
In the Controller
var self = this;// this is the controller which is aliased as ctrl at routing
var theData = yourService.FetchData(params).then(function(data){
self.tableData = data; // not going for the exact implementation.
},function(err){
manageError(err);// manage your errors here.
}));
In the HTML
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tr ng-repeat="var item in ctrl.tableData ">
<td>{{item.companyId}}</td>
<td>{{item.legalName}}</td>
<td>{{item.dbaName}}</td>
<td>{{item.formation}}</td>
</tr>
</table>

Related

extracting values from rows to use in a URL

I have generated a data table using the Datatables jquery plugin. The table is populated with JSON.
I want to extract cell values when I make a selection to use in a URL but I can't get it to work.
#I'm using django
import json
#my list
users = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']]
#my json
user_json = json.dumps(users)
<table class="table table-striped- table-bordered table-hover table-checkable" id="user-table">
<thead>
<tr>
<th>Age</th>
<th>Record ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
</table>
<script type="text/javascript">
var userData = {{user_json|safe}};
</script>
var SourceHtml = function() {
var dataJSONArray = userData;
var initTable1 = function() {
var table = $('#user-table');
// begin table
table.DataTable({
responsive: true,
data: dataJSONArray,
columnDefs: [
{
targets: -1,
title: 'Actions',
orderable: false,
render: function(data, type, full, meta) {
//this is where I need help. I need for each a-tag to link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}"
return '<i class="la la-edit"></i>';
},
},
],
});
};
return {
//main function to initiate the module
init: function() {
initTable1();
}
};
}();
jQuery(document).ready(function() {
SourceHtml.init();
});
I need a href link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}" in each a tag. however, I can't get the values from the cells.
Datatables columns.render option can be used to access full data source of current row.
By using columns.render as function type, we can use third (3)
parameter to access another column index form same row of data
source.
var userData = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']];
$('#example').dataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"title": 'Actions',
"render": function ( data, type, row, meta ) {
return 'Download';
}
} ]
} );

Datatable for pagination and searching for live data?

I tried using datatables for live data but my problem is, every time my data updates, I can't use searching and every time I use pagination, it goes back to first page. Can somebody knows what datatable plugin is compatible with angular?
Here is my code for realtime update of data:
angular.module('selectExample', [])
.controller('ExampleController', ['$scope','$interval', function($scope,$interval) {
$interval(function () {
$scope.register = {
regData: {
branch: {},
},
names: [
{name:"narquois"},{name:"vorpal"},{name:"keen"},
{name:"argol"},{name:"long"},{name:"propolis"},
{name:"bees"},{name:"film"},{name:"dipsetic"},
{name:"thirsty"},{name:"opacity"},{name:"simplex"},
{name:"jurel"},{name:"coastal "},{name:"fish"},
{name:"kraken"},{name:"woman"},{name:"limp"},
],
};
}, 1000);
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<table id="example" width="100%">
<thead>
<tr align="center">
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in register.names">
<td align="center">{{ person.name }}</td>
</tr>
</tbody>
</table>
</div>
Enable state saving and override state save/load handlers to use only the table's DOM id:
$('#example').dataTable( {
stateSave: true,
stateSaveCallback: function(settings,data) {
localStorage.setItem( 'DataTables_' + settings.sInstance, JSON.stringify(data) )
},
stateLoadCallback: function(settings) {
return JSON.parse( localStorage.getItem( 'DataTables_' + settings.sInstance ) )
}
} );
You have to initialize your DataTable with the option stateSave. It enables you to keep the pagination, filter values, and sorting of your table on page refresh. It uses HTML5's APIs localStorage and sessionStorage.
$('#example').dataTable( {
stateSave: true
});

How to fill a footable from a json

I have my html code like this defining a footable
<table class="table toggle-circle" id="exampleRowToggler">
<thead>
<tr>
<th data-field="marca">Marca</th>
<th data-field="modelo">Modelo</th>
<th data-field="placa">Placa</th>
<th data-field="chasis">Chasis</th>
<th data-field="vigencia_desde">Vigencia Desde</th>
<th data-field="vigencia_hasta">Vigendia Hasta</th>
<th data-hide="all">Clausulas</th>
<th data-hide="all">Exclusiones</th>
<th data-hide="all">Beneficios</th>
<th data-hide="all">Deducibles</th>
<th data-hide="all">Coberturas</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and I want to fill it from a .js file that contains a function with the data in json like this. I've tried some options but still can't get it and the last thing I've tried was this.
loadTable: function () {
var bt_data = [{
"marca": "HYUNDAI",
"modelo": "IONIQ",
"placa": "T02096577",
"chasis":"KMHC851CGHU029520",
"vigencia_desde":"22/05/2017",
"vigencia_hasta":"22/05/2018",
"clausulas": "clauuuuuusulaaas",
"exclusiones": "eeexclusioooonesss",
"beneficios": "beeeeneeefiiiciiiooosss",
"deducibles":"deeeeduuuuciiiibleeeessss",
"coberturas":"cooooobeeeertuuuuraaaasssss"
}];
$('#exampleRowToggler').footable({
"useParentWidth": true,
"columns": $.get('columns.bt_data'),
"rows": $.get('rows.bt_data')
});
}
help me please.
The columns and rows values that you are passing in to footable will be producing nothing at all unless you have a server side page listening for the "columns.bt_data" and "rows.bt_data" URLs and returning relevant JSON/array responses.
Here's what I think you wanted to do:
loadTable: function () {
var bt_data = [{
"marca": "HYUNDAI",
"modelo": "IONIQ",
"placa": "T02096577",
"chasis":"KMHC851CGHU029520",
"vigencia_desde":"22/05/2017",
"vigencia_hasta":"22/05/2018",
"clausulas": "clauuuuuusulaaas",
"exclusiones": "eeexclusioooonesss",
"beneficios": "beeeeneeefiiiciiiooosss",
"deducibles":"deeeeduuuuciiiibleeeessss",
"coberturas":"cooooobeeeertuuuuraaaasssss"
}];
//get Column JSON from first item in Rows array
var columnJSON = $.map(Object.getOwnPropertyNames(bt_data[0]), function (column) {
return {"name": column,"title": column}
});
$('#exampleRowToggler').footable({
"useParentWidth": true,
"columns": columnJSON, //Pass columns object through to footable
"rows": bt_data //Pass your existing rows array through to footable
});
}

how to populate jquery datatables with json?

I am using jquery datatable in my application, plugin link https://datatables.net/
I want to populate my datatable with JSON, but I am failed.here is my code.
HTML:
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
JS:
$(document).ready(function() {
console.log("hi ready");
$('#example').DataTable({
retrieve: true,
ajax: {
url: '/ProductLicensingApplication/feature/list',
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "code" },
{ "data": "description" },
{ "data": "isActive" }
]
});
} );
my json
but I am not able to populate data into the table as the table shows no data available in the table..you can see in the image
please tell me what is the problem in my code...
As written in documentation. The ajax.dataSrc option is used to tell DataTables where the data array is in the JSON structure. An empty string is a special case which tells DataTables to expect an array.
In your case JSON is an object and you should set dataSrc : 'features'
Ahmad,
Either set dataSrc : 'features' or if possible rename the attribute name 'features' to 'data' in the response data.

Add href hyperlink to row or field in datatable

I've seen a lot of questions about this, however I cannot seem to get it working.
I have a datatable but I cannot get it to work. I use python-flask with bootstrap and I change a pandas dataframe to a html table with to_html().
<table width="100%" class="table table-striped table-bordered table-hover dataTable" id="dataTables-example"><thead>
<tr style="text-align: right;">
<th>id</th>
<th>user</th>
<th>status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
and at the bottom of the body I have:
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
"bDestroy": true,
"deferRender": true,
"columns": [
{ "data": "id" },
{
"data": "weblink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
}
]
});
});
</script>
I've looked at a lot of awnsers however they all contain the data as json in the javascript while my data is already in the html.
Use columnDefs when you have a DOM <table> and only need to target one or few columns :
$('#dataTables-example').DataTable({
destroy: true,
deferRender: true,
columnDefs: [{
targets: 0, //<-- index of column that should be rendered as link
render : function(data, type, row, meta){
if (type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
}]
})
It works here -> http://jsfiddle.net/j9ez0sbj/
You have 3 columns in your html table but only define 2 columns in your initialization.
From datatables documentation for the columns initialization option:
Note that if you use columns to define your columns, you must have an entry in the array for every single column that you have in your table (these can be null if you don't wish to specify any options).
Depending on what your intent is, at the very least you need to add a definition for the third column, so something like this:
"columns": [
{ "data": "id" },
{
"data": "weblink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
},
{ "data": "status" } // Third column definition added
]

Categories

Resources