Add edit/delete icon to row of data populated by JSOn (AjaxCall) - javascript

I have an HTML table which is being populated by a JSON (ajax call). In the Edit and Delete columns of the table I need to have an icon to edit or delete the data on each row.
I don't know how to add the icon when the table is populated by the JSON.
Following is my code:
//JSON which is populating the table. Register.js
$(document).ready(function() {
var allRegister = AjaxCall(apiUrl, mthdGetReleasesFullList, null,
{
});
var data=allRegister.responseText;
alert("testing"+ data);
var jsonResponse = JSON.parse(data);
//var table = $('#contact-data').DataTable({
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
],
"order": [[1, 'dsc']]
});
});
Html code for table:
<link rel="stylesheet" href="entity/Register/css/Register.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Page specific JS -->
<script src="entity/Register/js/Register.js"></script>
<div class="container-full">
<div class="heading-1">
<input type="button" id="btn-AddUser" value="Add Release" style="font-size:14px;color:teal;text-align: left">
<h1>
</h1>
<div class="modular-box-text inset">
<div class="retgister-table-holder">
<h2>Pre-Release Access Register:</h2>
<br>
<div class="register-table" >
<table id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusIDth>
<th>Edit<th>
<th>Delete </th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>

You need to work with the render option of the columns objects - documentation here. When you specify the targeted ID of your desired action (i presume it is ReleaseID) you just create more columns with that ID as data object and adjust the column renderer by giving it a custom render method. Since you specified ReleaseID as data, you can re-use that value in the render method as first argument.
In the example below you can see how to achieve this - You can very easily replace Edit and Delete text with <img /> tags referencing the icons you want to have for each action.
// Faking a request
var response = [
{ "ReleaseID": "1",
"ReleaseName": "Release A",
"DivisionID": "10",
"StatusID": "1"
}, {
"ReleaseID": "2",
"ReleaseName": "Release B",
"DivisionID": "9",
"StatusID": "2"
}, {
"ReleaseID": "3",
"ReleaseName": "Release C",
"DivisionID": "9",
"StatusID": "1"
}, {
"ReleaseID": "4",
"ReleaseName": "Release D",
"DivisionID": "10",
"StatusID": "2"
}, {
"ReleaseID": "5",
"ReleaseName": "Release E",
"DivisionID": "11",
"StatusID": "1"
}];
$(document).on('ready', function() {
$('#register-data').dataTable({
"data": response,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{
"data": "ReleaseID",
"render": (data, type, row, meta) => `Edit`
}, {
"data": "ReleaseID",
"render": (data, type, row, meta) => `Delete`
}
],
"order": [[1, 'dsc']]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusID</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Thanks for your response.
I used the following to get Edit and Delete buttons to appear on all rows of table
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{"data":null, "defaultContent": "<button class='btn-Edit'>Edit</button>"},
{"data":null, "defaultContent": "<button class='btn-Delete'>Click!</button>"},
],
"order": [[1, 'dsc']]
});

Related

Datatables not populating with data from RestAPI call

when trying to read back my api into data tables im getting an error "Cannot read property 'length' of undefined"
my table is as follows:
<div class="container-fluid d-flex flex-column min-vh-100 justify-content-center align-items-center">
<div class=" row d-flex justify-content-center ">
<!-- Table -->
<table id="movieTable" class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Year</th>
</tr>
</thead>
<tbody id="list-list">
</tbody>
</table>
</div>
</div>
And my script is as follows:
<script>
$('#movieTable').DataTable({
"ajax": "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id=1",
dataSrc: "",
"columns": [
{
"data": "Title"
}, {
"data": "Year"
},
]
});
</script>
I can't see exactly what I'm doing wrong, any help appreciated!
Edit, after the advice given I've edit my script to be the following:
<script>
$('#movieTable').dataTable({
ajax: {
url: "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id=2",
dataSrc: "tv_shows",
"columns": [
{
"Title": "Title"
}, {
"Year": "Year"
},
]
},
});
</script>
My JSON response is as follows:
{
"status": "true",
"message": "Customer Details",
"tv_shows": {
"id": "456",
"Title": "Vampire Knight",
"Year": "2008",
"Age": "16+",
"IMDb": "7.5",
"RottenTomatoes": "",
"Netflix": "1",
"Hulu": "1",
"Prime": "0",
"Disney": "0"
}
}
I think my api might be the problem, i've set it to return values based on the ID queried. if i don't add ?id='x' my response is as follows:
{
"status": "false",
"message": "No customer(s) found!"
}
The code used to build my api is:
//return JSON by id
if (isset($_GET['id']) && $_GET['id']!="") {
$id = $_GET['id'];
$query = "SELECT * FROM tv_shows WHERE id={$id}";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$tableData['id'] = $row['id'];
$tableData['Title'] = $row['Title'];
$tableData['Year'] = $row['Year'];
$tableData['Age'] = $row['Age'];
$tableData['IMDb'] = $row['IMDb'];
$tableData['RottenTomatoes'] = $row['RottenTomatoes'];
$tableData['Netflix'] = $row['Netflix'];
$tableData['Hulu'] = $row['Hulu'];
$tableData['Prime'] = $row['Prime'];
$tableData['Disney'] = $row['Disney'];
$response["status"] = "true";
$response["message"] = "Customer Details";
$response["tv_shows"] = $tableData;
} else {
$response["status"] = "false";
$response["message"] = "No customer(s) found!";
}
echo json_encode($response); exit;
Updated api code to return a collection of objects rather than just one
JSon resposne as follows:
{
"data": [
{
"Title": "Breaking Bad",
"Year": "2008",
"Age": "18+",
"IMDb": "9.5",
"Rotten Tomatoes": "96%",
"Netflix": "1",
"Prime": "0",
"Hulu": "0",
"Disney": "0"
},
{
"Title": "Stranger Things",
"Year": "2016",
"Age": "16+",
"IMDb": "8.8",
"Rotten Tomatoes": "93%",
"Netflix": "1",
"Prime": "0",
"Hulu": "0",
"Disney": "0"
},
Datatables script is:
<script>
$('#movieTable').DataTable({
"processing": true,
"serverSide": true,
"sPaginationType": "full_numbers",
"order": [],
"ajax": {
"url": "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi2.php",
"type": 'get',
"dataType": 'json'
},
"columns": [
{ "data": "Title" },
{ "data": "Year" },
]
});
</script>
Still no data in the datatables!
Got it working thanks to #andrewjames for his help!
I had to change my api to output an array of objects rather than one object and ensure JSON output matched the output defined in datatables documentation.
Working JS code:
<script>
$(document).ready(function() {
$('#movieTable').DataTable( {
"ajax": {
"url": "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi2.php",
"dataSrc": "data"
},
"columns": [
{ "data": "id" },
{ "data": "Title" },
{ "data": "Year" },
{ "data": "Age" },
{ "data": "IMDb" },
{ "data": "Rotten Tomatoes" },
]
} );
} );
</script>
HTML table structure:
<div class="container-fluid d-flex flex-column min-vh-100 justify-content-center align-items-center">
<div class=" row d-flex justify-content-center ">
<!-- Table -->
<table id="movieTable" class="display" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Title</th>
<th>Year</th>
<th>Age</th>
<th>IMDb</th>
<th>Rotten Tomatoes</th>
</tr>
</thead>
</table>
</div>
</div>

DataTables Jquery Ajax Object not finding array columns

I'm trying to use jquery.dataTables with an Ajax data source to pull json data into a html table.
I'm facing an issue where it's not able to find the data I'm looking for in the JSON response and I'm struggling to find where my issue lies. I'm getting an undefined error as it's not able to match the data columns I requested.
In the Snipped-I removed the URL but here's a sample of the object structure returned.
{
"success": true,
"result": [
{
"type": "gift",
"name": "Gift",
"rewards": [
{
"name": "Item Name",
"image_url": "https://xxx.jpg",
"minimum_display_price": "500+ bucks",
"description": {
"text": "text here",
"html": "html here"
},
"disclaimer_html": "disclaimer",
"warning": null,
"denominations": [
{
"id": "5ca1737f1sdasdsadsad2cb5f004cc0d564",
"name": "Name",
"price": 500,
"display_price": "500",
"available": true
}
]
}
]
}
]
}
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "myurlishere",
"columns": [
{ "result[0]": "name" }
//{ "result": "rewards.name"}
// {"data": "name"}
]
} );
} );
<script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.colVis.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.print.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.bootstrap.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js" type="text/javascript"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
</tr>
</tfoot>
</table>
Looks like you have some nested data objects and while it might be possible to deal with this directly within DataTable it's likely easier to pre-process the data before handing it off to DataTable for rendering. This would convert your nested data into a flat array of reward objects, which should make rendering it easier.
(async function() {
const rawData = await fetch("your_url").then(data => data.json());
const finalData = rawData.result.map(category => category.rewards).flat(1);
$("#example").DataTable({
data: finalData,
columns: [{ data: "name" }]
});
})();
Might be you need to change your code , just check following way,
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "myurlishere",
"columns": [
{ "data": "name" },
{ "data": "rewards[, ].name" },
{ "data": "rewards[, ].image_url" },
{ "data": "rewards[, ].description.text" },
{ "data": "rewards[, ].denominations[,].name" },
]
} );
} );

Sending Json data as an object into DataTables

I have been trying to use DataTables. But after my Ajax request i get a Json object which i cannot pass into dataTables.
The Json object i receive is the following
{"data": [{"attributes": {"purchasedate": "04/01/2017", "medication": "meds", "cost": 100.0, "expirydate": "04/03/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Meds", "cost": 100.0, "expirydate": "04/02/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Super Meds", "cost": 267.0, "expirydate": "04/11/2017", "quantity": 250.0}, "type": "medical_inventory"}], "links": {"self": "/medical_inventory/"}}
Following is my HTML code
<table id="myTable" class="display" cellspacing="0" width="90%">
<thead>
<tr>
<th>Medication</th>
<th>Medication Quantity</th>
<th>Mediaction Cost</th>
<th>Purchase Date</th>
<th>Expiry Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Medication</th>
<th>Medication Quantity</th>
<th>Mediaction Cost</th>
<th>Purchase Date</th>
<th>Expiry Date</th>
</tr>
</tfoot>
</table>
The Ajax request i do is the following
$(document).ready(function () {
$.ajax({
url : '/api/medical_inventory/',
type : 'GET',
dataType : 'json',
success : function(data) {
assignToEventsColumns(data);
}
});
function assignToEventsColumns(data) {
var table = $('#myTable').dataTable({
"bAutoWidth" : false,
"aaData" : data,
"columns" : [ {
"data" : "medication"
}, {
"data" : "quantity"
}, {
"data" : "cost"
}, {
"data" : "purchasedate"
}, {
"data" : "expirydate"
} ]
})
}
});
This is the output i am currently getting
You were very nearly there:
function assignToEventsColumns(data) {
var table = $('#myTable').dataTable({
"bAutoWidth": false,
"aaData": data.data,
"columns": [{
"data": "attributes.medication"
}, {
"data": "attributes.quantity"
}, {
"data": "attributes.cost"
}, {
"data": "attributes.purchasedate"
}, {
"data": "attributes.expirydate"
}]
})
}
All you were missing was the structure of your JSON, you needed to add attributes. as well as your data.data :-D.Working JSFiddle here.
Try mapping the data to remove the attributes property of each object
success : function(data) {
data.data = data.data.map(function(item){
return item.attributes;
});
assignToEventsColumns(data);
}

Could not load Datatable with JSON objects

I am trying for pagination from dynamic data. I started using Datatable but I am not able to load Datatable with JSON Objects.
Please find my code below:
function drawTable(data) {
$('#t01').DataTable( {
ajax: {
"aaData": data,
"dataSrc": ""
},
"aoColumns": [
{ "mdata": "UserName" },
{ "mdata": "AppName" },
{ "mdata": "OS" },
{ "mdata": "Changes" },
{ "mdata": "Time" }
]
} );
}
My JSON:
[{
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : true to false, ",
"Time": "2016-03-22 11:36:09"
}, {
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : false to true, ",
"Time": "2016-03-22 11:44:11"
},..
My html page:
<table id="t01" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>UserName</th>
<th>AppName</th>
<th>OS</th>
<th>Changes</th>
<th>Time</th>
</tr>
</thead>
</table>
The table is not getting loaded but loading ... appears in table. I have checked, JSON is in correct format.
I edited my code:
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"processing" : true,
"data": data,
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}
and now my table is loaded with blank columns and I am getting error as:
DataTables warning: table id=t01 - Requested unknown parameter 'UserName' for row 0, column 0.
Your code work fine for me. This is how I used it :
first : I create a json.php who contains the following code :
[{
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : true to false, ",
"Time": "2016-03-22 11:36:09"
}, {
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : false to true, ",
"Time": "2016-03-22 11:44:11"
}]
After I create an other page test.php with these following codes :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="https://www.datatables.net/release-datatables/extensions/TableTools/css/dataTables.tableTools.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="t01" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>UserName</th>
<th>AppName</th>
<th>OS</th>
<th>Changes</th>
<th>Time</th>
</tr>
</thead>
</table>
</body>
<script type="text/javascript">
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"processing" : true,
"data": data,
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}
$(document).ready(function() {
$.ajax({
url: "json.php",
dataType: "json",
success: function(data) {
drawTable(data);
}
});
});
</script>
</html>
And this is the result :
try this, i think this useful
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"bProcessing": true,
"bServerSide": true,
"bFilter" : false,
"sAjaxSource": "data.php",//your data source
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}

Edit jQuery Datatable fields

I would like to output a bootstrap label for one value of a field in a JQuery dataTable. This fields possible values can be '0' or '1' and depending on the result I want to decide which bootstrap label I want to output in the dataTable. Unfortunately I don't know how I can do this if statement for this case.
My JQuery:
$(document).ready(function() {
$('#accountOverview').dataTable( {
"ajax": {
"url": "/database/accounts.php",
"data": {"action": "selectAccounts"},
"dataSrc": ""
},
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
{ "data": "profitDay" },
{ "data": "playerName" },
{ "data": "tradepileCards" },
{ "data": "tradepileValue" },
{ "data": "enabled" }
],
"autoWidth": false
});
});
I need to use something like this for the result of the "enabled" field:
if(enabled==1) <label class="label label-success">Online</label>
else <label class="label label-error">Offline</label>
HTML Table:
<table id="accountOverview" class="table datatable">
<thead>
<tr>
<th>E-Mail</th>
<th>Platform</th>
<th>Coins</th>
<th>Profit last 24h</th>
<th>Playername</th>
<th>Tradepile Cards</th>
<th>Tradepile Value</th>
<th>Status</th>
</tr>
</thead>
<tbody id="accountList">
<!-- List all accounts -->
</tbody>
</table>
The label needs to be in the field "status" = the last each row.
Following dataTable's "draw" (which happens after AJAX loads your data), you can look up the last td of each row and use wrapInner() to inject the HTML you want. So, in your case, try:
var apply_label=function(){
$('#accountOverview').find('td:last-child').not(':has(.label)').each(function(){
if( this.innerHTML==="1"){
$(this).wrapInner('<span class="label label-success"></span>');
}
else {
$(this).wrapInner('<span class="label label-danger"></span>');
}
});
};
$('#accountOverview').dataTable( {
"ajax": {
"url": "/database/accounts.php",
"data": {"action": "selectAccounts"},
"dataSrc": ""
},
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
{ "data": "profitDay" },
{ "data": "playerName" },
{ "data": "tradepileCards" },
{ "data": "tradepileValue" },
{ "data": "enabled" }
],
"autoWidth": false,
"drawCallback": function( settings ) {
apply_label();
}
});
Notes:
I think you want span (not label).
I think you want .label-danger (not .label-error).
Check it out at http://jsfiddle.net/jhfrench/wrkkbcf1/.

Categories