I got this table code
<table id="tabel_komponen" class="table table-hover">
<thead>
<tr>
<th>ID Komponen</th>
<th>Nama Komponen</th>
<th>Ekuivalen SKS</th>
<th>Ekuivalen Jam</th>
<th>Indikator</th>
</tr>
</thead>
<tbody id="badan_tabel" >
</tbody>
</table>
And I use the dataTable Plugin to make it looks good, here's the code
$(document).ready( function () {
$('#tabel_komponen').DataTable();
} );
I want to get the data for the table from this URL : http://paramadina.net:18011/data/psc_komponen
I already try this code
$(document).ready( function () {
$('#tabel_komponen').DataTable();
} );
var table = $('#tabel_komponen').DataTable( {
ajax: 'data.json'
} );
alert( 'http://paramadina.net:18011/data/psc_komponen'+table.ajax.url() );
but it dont worked...And I want to add an edit button into the table
Thanks!!!!
If http://paramadina.net:18011/data/psc_komponen/data.json is the URL where JSON file is located, then use the code below:
$(document).ready( function () {
$('#tabel_komponen').DataTable({
ajax: 'http://paramadina.net:18011/data/psc_komponen/data.json'
});
});
As noted by #davidkonrad, unless paramadina.net allows cross-domain requests, the code above will fail. You need to allow such requests or use JSONP or other alternative methods to get the data.
Related
What I want to do is to let my users select multiple rows in a table and them hit a button to send this data back. My JS script file looks has the following:
<script>
$(document).ready(function () {
// Setup - add a text input to each footer cell
$('#example tfoot th').each(function () {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
$('#example tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#button').click(function () {
alert(table.rows('.selected').data().length + ' row(s) selected');
});
// DataTable
var table = $('#example').DataTable({
initComplete: function () {
// Apply the search
this.api()
.columns()
.every(function () {
var that = this;
$('input', this.footer()).on('keyup change clear', function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
},
});
});
</script>
My HTML code is as follows:
<form action="/get1" method="POST" name = 'input'>
<button id="button">Row count</button>
<table id="example" class="table table-striped">
<thead>
<tr>
<th scope="col">Index</th>
<th scope="col">Col2</th>
<th scope="col">Col3</th>
<th scope="col">Col4</th>
</tr>
</thead>
<tbody>
{% for item in rows %}
<tr>
<td>{{item[0]}}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>Index</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</tfoot>
</table>
</form>
I need some help with JS and HTML to POST values (such as row index) to the backend that the backend can read.
Let's assume you have added the following DataTables Select resources to the head of your web page:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.4.0/css/select.dataTables.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.4.0/js/dataTables.select.js"></script>
Then you can enable the extension by adding the following option to your DataTable:
select: true
Now you can experiment with selecting and de-selecting rows. You can use the CTRL and SHIFT keys to select multiple rows.
In your button click event you can now use the selected() function I mentioned in my comment - for example:
$('#button').click(function () {
selected_ids = [];
table.rows().every(function () {
if ( this.selected() ) {
selected_ids.push( this.data()[0] );
}
});
console.log( selected_ids );
});
This will capture an array of IDs from the selected rows.
Note how it uses very similar logic to the columns().every() function you already have - except it uses rows().every() to iterate over the rows in the DataTable - not only the visible rows in the current page, but also all rows in other DataTables pages (if there multiple pages of table data).
The next step is a completely different question: How to submit the IDs in that array to your Flask back end.
That has been covered elsewhere in various questions - for example: jQuery Ajax POST example with PHP. Yes, this mentions PHP, but the jQuery piece is independent of the server technology.
That question has 25 answers, and there are various other questions along similar lines, which should help you. If you get stuck you can ask a new question with the specific problem you are facing.
But, basically, instead of my console.log( selected_ids );, you would use a jquery Ajax call: $.ajax( { ... } ); to send the data to Flask.
I'm trying to display a table on a new page by calling an API and loading the data in the table. This page is loaded on click of a menuItem.
But the issue I'm facing is that the table is displaying, but not the data I'm intending to. I know that I'm able to fetch the data from the API since i can see that in the console log.
Here is the code:
In this first html file im clickling the menu and calling my next html page i want to load
and also im giving my id="covidLink" which im calling in my JS FILE.
pan.html
<div class="navbar">
<a class="covidText" id="covidLink" href="covidStatusUpdate.html">Covid-19</a>
</div>
In the below js file im making a call to the api and appending the data in tbody.
Fetchdata.js
$(document).ready(function () {
$("#covidLink").click(function () {
console.log("Link clicked...");
requestVirusData();
});
});
function requestVirusData() {
$.getJSON('https://api.covid19api.com/summary',
function(data){
var countries_list = data.Countries;
//console.log(countries_list);
$(countries_list).each(function(i, country_dtls){
$('#totalbody').append($("<tr>")
.append($("<td>").append(country_dtls.country))
.append($("<td>").append(country_dtls.TotalConfirmed))
.append($("<td>").append(country_dtls.TotalDeaths))
.append($("<td>").append(country_dtls.TotalRecovered)));
});
})
}
and lastly
statusUpdate.html
<table class="table table-striped table-bordered table-sm" cellspacing="0" width=80%>
<thead>
<tr>
<th>Country</th>
<th>TotalConfirmed</th>
<th>TotalDeaths</th>
<th>TotalRecovered</th>
</tr>
</thead>
<tbody id="totalbody">
</tbody>
</table>
What am I supposed to do ? I have to admit that I'm lost here.
I don't think you quite understand how AJAX works. You're handling a click on "covidLink". This does two things simultaneously.
it tells the browser to navigate away from the current page and go to statusUpdate.html instead.
it runs the requestVirusData() function. This gets the data from the API and returns it to the page.
But the problem is: the API call returns the data to the page where the script was called from - i.e. it returns it to pan.html. And you've just told the browser to move away from that page. Also, pan.html doesn't contain a table to put the returned data into.
The logical solution here is to link to fetchdata.js from statusUpdate.html instead, and tweak the code slightly so it runs when that page loads, rather than on the click of a button:
$(document).ready(function () {
console.log("page loaded...");
requestVirusData();
});
As suggested by ADyson i did changes in my code and now im able to display the table with data.
Here are my code changes:
statusUpdate.html
<tbody id="tbody">
<script>
var datatable;
fetch('https://api.covid19api.com/summary')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var countries_list = data.Countries;
var tbody = document.getElementById("tbody");
// clear the table for updating
$('table tbody').empty();
// hide the table for hidden initialize
$('table').hide();
// loop over every country
for (var i in countries_list) {
var country_dtls = countries_list[i];
// replace -1 with unknown
for (var o in country_dtls) {
if (country_dtls[o] == -1) country_dtls[o] = 'Unknown';
}
$('table tbody').append(`
<tr>
<td>${country_dtls.Country}</td>
<td>${country_dtls.TotalConfirmed}</td>
<td>${country_dtls.TotalDeaths}</td>
<td>${country_dtls.TotalRecovered}</td>
</tr>`);
}
}
// }
</script>
</tbody>
pan.html
<a class="covid" href="statusUpdate.html">Covid-19</a>
and now i do not need fetchdata.js obviously.
Hope this helps someone stuck like me :)
Below is the classical issue which I am facing during my app development.
I have an array of JSONObjects in my spring controller that I have to iterate in the jsp;
Also another status attribute called JSONArrayStatus is set that suggests if JSON array is empty or not.
Using jquery if JSONArray is empty I will show noDataImageDiv otherwise will show tableDIV (Binding the data from JSONArray using JSTL)
The problem I am facing is as below.
1. Edit a row in the table and click on Update. At this time I make an Ajax Call say, "UpdatedUser", which will return all the records along with the updated records. I could use refresh however thats not a recommended user experience and hence a no no.
To reflect the updated users in the table, I use jquery as below
clearing table rows table.clear().draw()
Loop the result set as follows.
redraw code
function reDrawExternalContactUsers(externalUsers) {
table.clear().draw();
var row = "";
$.each(externalUsers, function (i, field) {
row = '<tr><td></td><td></td><td class="edit">edit</td></tr>';
$("#tableDIV").append(row);
});
}
afetr this redraw or refresh process
This function is NOT working
$(".edit").click(function(){
});
This function is working
$("#tableDIV .edit").click(function(){
});
Suggest a better way of refreshing table rows, if any.
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td></td>
<td></td>
<td class="edit">edit</td>
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
html code :
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td class="user-name"></td>
<td></td>
<td class="edit" data-user-id="">edit</td> //set user_id in attr data-user-id
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
jquery code :
you should use click event on document
$(document).on('click', '.edit', function () {
var btn = $(this);
var user_id = btn.attr("data-user-id"); //user_id of user will update
// extra user data
$.ajax({
method: "POST",
url: url,
data: {
'id': id,
// extra data to send
},
success: function (data) {
if (data.status) // successfully user updated
{
var user = data.user;
/* you can set user data like this */
btn.closest('tr').find('.user-name').html(user.name);
}
}
});
});
I am using bootstrap table to display data from my MongoDB, using a mongoid query. I would like to refresh the table at an interval of 5 minutes. I've read the documentation, but being new to Javascript, I'm not sure how to accomplish this - whether to use an Ajax call or just a setTimeout() function, etc.
This is my table code:
<table id="table" data-show-refresh="true" data-row-style="rowStyle" data-toggle="table" data-url="http://maccdx160121:4567/api/v1/currentsat*">
<thead>
<tr>
<th data-field="initials">Initials</th>
<th data-cell-style="cellStyle" data-field="sector">Sector</th>
<th data-field="cjs">CJS</th>
</tr>
</thead>
</table>
This is my Mongoid query, if it helps:
get '/currentsat*' do
#SatTransaction.where( current: true, :initials.ne => nil, :position.in => ["RDR", "SPVR", "OJI"] ).to_json
SatTransaction.where( current: true, :shift_duration.ne => 0, ).and(SatTransaction.or({:position.in => ["SPVR", "RDR", "OJI"]},{sector: "BREAK"}).selector).to_json
end
end
before do
cache_control :no_cache
end
def with_captured_stdout
old_stdout = $stdout
$stdout = StringIO.new('', 'w')
yield
$stdout.string
ensure
$stdout = old_stdout
end
Thanks for any help!!
I think you remove the table and recreate that:
setInterval(function(){
$('#table').remove();
$('#Table_Parent').append(Table_Html);
}, 5000);
I think you need to do the both. You need to get the data from the server using ajax and then reload it into the datatable.
Only refreshing the data table will just reload the data what you have in your html but you need to refresh because it will reload the chaged data.
as #Farzin Kanzi code, inside the set time out make the ajax call and reload with server data
setInterval(function(){
$.ajax(
...
success(response) {
Table_Html = resopnse
}
)
$('#table').remove();
$('#Table_Parent').append(Table_Html);
}, 5000);
I was given the following JSON format and I am having a difficult time getting to the information. I want to put it into a data table.
"data": {
"HeadingOne":{
"Columns":["Row1", "Row2"],
"Data":[["firstData", "secondData"]]
}
}
I am told that I should be able to access this data but I have absolutely no clue how to get to "firstData" in datatables. (from datatables.net) This is what I have tried
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "<%= request.getContextPath()%>/ajax/mastermenu.txt",
"columns":[
{"data": "HeadingOne.Data.Row1"}
]
} );
} );
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Row1</th>
<th>Row2</th>
</tr>
</thead>
</table>
As others have noted, you're missing a } at the end. After you fix that this should work.
Assuming the object is called data, this will get you "firstData"
console.log(data.HeadingOne.Data[0][0]); // "firstData"
Yeuch. But:
var data = {
"HeadingOne":{
"Columns":["Row1", "Row2"],
"Data":[
["firstData", "secondData"]
]
}
}
var firstData = data['HeadingOne']['Data'][0][0]
Note: I had to add a final } to that block otherwise it was not valid
If you're trying to access firstData by name, hopefully it's obvious that it won't work as it's contained in an array within an array (hence the [0][0]).