Data table initialize after table body replace (ajax) - javascript

I have a datatable it have a search box (date range filter) once i click the search button table body replace according to the filter(ajax).
my problem is i cant initialize table after ajax success.
HTML
<table data-page-length="20" id="occupancy" class="ui small celled table segment display" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Date</th>
<th>Arrivals</th>
<th>Departures</th>
<th>Occupied</th>
<th>Available</th>
<th>Occupancy</th>
</tr>
</thead>
<tbody id="occupancyBody">
</tbody>
</table>
Ajax
type: 'POST',
url: "../system/user/modules/" + MODULE_NAME + "/controller.php",
data: "action=filterOc&" + url_data,
success: function (resultData) {
$('#occupancyBody').html(resultData);
$('#occupancy').dataTable();
}
});
sample screenshot

You can use below mentioned code to reinitialize table after ajax call.
While defining datatable, you can store in a variable.
var myTable = $('#occupancy').DataTable({ // all your configuration });
Now after ajax call you can call below line.
myTable.ajax.reload();
also remove this line in ajax:success function.
$('#occupancy').dataTable();
Let me know if it not works.

Please check here
$(document).ready(function(){
var table = $('#occupancy').dataTable();
$.ajax({
type: 'POST',
url: "../system/user/modules/controller.php",
data: "action=filterOc&",
success: function (resultData) {
$('#occupancyBody').html(resultData);
table.ajax.reload();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/css/dataTables.bootstrap.css" rel="stylesheet"/>
<table data-page-length="20" id="occupancy" class="ui small celled table segment display" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Date</th>
<th>Arrivals</th>
<th>Departures</th>
<th>Occupied</th>
<th>Available</th>
<th>Occupancy</th>
</tr>
</thead>
<tbody id="occupancyBody">
</tbody>
</table>

The ajax.reload() API function should only work if you included the ajax option in Datatable's initialization (see here).
In this case, I'd recommend to add destroy:true to the initialization of Datatables, something like this:
$('#occupancy').DataTable({ destroy:true})
This would allow you to re-create the table every time the ajax call is successful.

hi i guess you selected wrong body id :
$('#occupancyBody').html(resultData);
but in your html :
<tbody id="dailyAct">
hope it's help,

Related

How to reload / refresh the html table using jquery

Below I've added my full Index.cshtml code. In ajax call it's hitting to success method. but i'm not able to reload or refresh the table without page refresh.
The below code is simple while clicking the submit button for filters i'm calling SubmitFilter method it redirect to c# method there i'm storing the results in a JArray variable.. then trying to reload the table...
this is the sample output screen
I've tried these
$("#tblTransactions").DataTable().draw();
$("#tblTransactions").DataTable().ajax.reload();
But it's not working for me. please Let me know if you got any idea ..thanks in advance..
#page
#model IndexModel
#{
Layout = "_Layout";
}
<script>
$(document).ready(function () {
$("#tblTransactions").DataTable();
});
function SubmitFilter()
{
var transactionNumb = $("#transactionNumber").val();
var cardHolderName = $("#cardHolder").val();
alert("SubmitFilter");
$.ajax({
type: "GET",
url: "https://localhost:7197/Transactions?transaction_number="+transactionNumb+"&cardholder="+cardHolderName,
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data)
{
}
});
}
</script>
<a style="max-width: 100px;max-height: 40px;margin-left: 10px;" href="#" onclick="SubmitFilter();" class="btn btn-primary">SUBMIT</a>
<table id="tblTransactions" class="table table-bordered table-condensed table-striped table-hover">
<thead>
<th scope="col">Transaction No</th>
<td scope="col">Type</td>
<td scope="col">Status</td>
</thead>
<tbody>
#foreach (dynamic transaction in #Model.Transactions)
{
<tr>
<td>#transaction.transaction_number</td>
<td>#transaction.type</td>
<td>#transaction.status</td>
</tr>
}
</tbody>
</table>

Show Data From JSON to HTML Table

I want to Show data from API JSON to html table
this is the link
https://openexchangerates.org/api/latest.json?app_id=c8e005009e5946f58356aa9a5fa7f5dd
<html>
<body>
<table>
<thead>
<tr>
<th>Currency</th>
<th>Value</th>
<th>selling rate</th>
<th>buying rate</th>
</tr>
</thead>
<tbody>
<tr>
<td>data from api</td>
<td>data from api</td>
</tr>
</tbody>
</body>
</html>
All I want to know is how to get data from API
Thanks
Make an ajax call to the above the API using
$.ajax({
type: "Get",
url: 'https://openexchangerates.org/api/latest.jso',
data: {app_id:c8e005009e5946f58356aa9a5fa7f5dd}
success:function(data){
//do something like this
var tbody_str="";
$(data.rates).each(function(key,value){
tbody_str = tbody_str + "<tr><td> data.key</td><td>data.value</td></tr>
});
});
If you are using simple jquery. So I prefer constructing your tablerows as string and append it to table body.
Without Jquery:
https://blog.garstasio.com/you-dont-need-jquery/ajax/
With Jquery:
How to parse JSON data with jQuery / JavaScript?

Datatables with JSON dynamic content, lose table features

I'm currently trying to fill dynamically a table with content retrieved from a JSON Object.
Here is the table:
<table id="datatable_tabletools" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th data-hide="phone">ID</th>
<th data-class="expand">Nom</th>
<th data-hide="phone">Commentaires</th>
<th data-hide="phone,tablet">Date</th>
<th data-hide="phone,tablet">Attachements</th>
<th data-hide="phone,tablet">Actions</th>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
I have multiple interesting features in the table such as a search option, a filter, sort, export as PDF, etc,....those features are working properly if I'm including static content such as:
<tr>
<td>33</td>
<td>Bevis</td>
<td>1-955-717-0835</td>
<td>Est Ac Inc.</td>
<td>7424</td>
<td>Ichtegem</td>
</tr>
but as soon as I retrieve data table content from My JSON object, I'm not able to use those features anymore, sort doesn't work, search neither.
Here is the JavaScript I'm using:
$(document).ready(function() {
$.get('getAllDocuments', function(responseJson) {
if (responseJson != null) {
var table1 = $("#table");
$.each(responseJson, function(key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['id']);
rowNew.children().eq(1).text(value['nom']);
rowNew.children().eq(2).text(value['commentaire']);
rowNew.children().eq(3).text(value['date']);
rowNew.children().eq(4).text(value['id']);
rowNew.children().eq(5).html("Voir Supprimer");
rowNew.appendTo(table1);
});
}
});
});
My table is filled correctly, but not all the functions associated. any idea on how I can fill my table with JSON content in a proper way?
I think you can use ajax option of DataTables like:
var table = $('#example').DataTable( {
ajax: 'data.json'
});
P.S. here is the documentation

How do I use data returned from PHP to build out an HTML table?

I have a php file that is reaching out and touching a mongo db and building a bunch of table tags. When I replace the script tag code below with the php code it works fine and builds out the table.
When I try to get the php results from the called page I manage to get the table text into the data variable ... if I alert it I see all the table tags and data that is generated from my .php page ... but I'm not sure how to embed that code inline in the HTML right after the th tags ... if I do a document.write(data) inside the script it seems to overwrite the whole page with just the data that was generated from the .php page ... it doesn't append it after the th row. Thank you in advance for any advice.
<table class="table table-striped table-hover">
<tr>
<th>Agency</th>
<th>POC</th>
<th>POC Phone</th>
<th>Address</th>
</tr>
<script>
var data_from_ajax;
$.get('build-agency-table.php', function(data) {
data_from_ajax = data;
alert(data);
});
</script>
</table>
And this is returned by the php script
<tr><td>BACODA</td><td>Kristi Smith</td><td>211.444.2222</td>
I think the script tag belong outside of the table.
And using the tbody thead will help you to differentiate the static (heading) and dynamic (from ajax) content.
<table>
<thead>
<tr>
<th>Agency</th>
<th>POC</th>
<th>POC Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody id="to_fill">
</tbody>
</table>
<script>
var data_from_ajax;
$.get('build-agency-table.php', function(data) {
data_from_ajax = data;
$("#to_fill").html(data_from_ajax);
});
</script>
Try this
<table class="table table-striped table-hover">
<tr>
<th>Agency</th>
<th>POC</th>
<th>POC Phone</th>
<th>Address</th>
</tr>
<tbody id="tablebody"></tbody>
<script>
var data_from_ajax;
$.get('build-agency-table.php', function(data) {
data_from_ajax = data;
$('#tablebody').html(data);
alert(data);
});
</script>
</table>
You need to add the html content to a container using javascript.
<table>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
</tr>
<tr id="myRow"></tr>
</table>
<script>
$.get('build-agency-table.php', function(data) {
$("#myRow").html(data); //Add the html content into "myRow"
});
</script>

ajax post from ajax get

I'm trying to post on ajax from a ajax get.
Here is my code below that I'm using:
$(window).load(function() {
$.ajax({
url: "/masterScreen/ajaxdealerpaid/{{$id}}",
type: "GET",
data: {},
success: function(data) {
document.getElementById("dealerPaid").innerHTML=data;
}
});
});
And then i'm trying:
$(".pay").click(function(){
alert('Order #'+id+' has been marked as paid for '+amountPaid+'');
var id = $(this).attr('data-id');
var amountPaid = $("#payAmount_"+id).val()
$.ajax({
url: "/masterScreen/dealermarkpaid/"+id+"/"+amountPaid,
type: "POST",
data: {},
success: function(data) {
alert('Order #'+id+' has been marked as paid for '+amountPaid+'');
location.reload();
}
});
});
My HTML is...
<table style="width: auto;" class="table table-striped table-condensed" border="0" cellspacing="0" cellpadding="0">
<thead class="navbar-static-top" style="display:block; margin:0px; cell-spacing:0px; left:0px;">
<tr>
<th class="span2">Quote ID</th>
<th class="span4">Customer name</th>
<th class="span4">Connection date</th>
<th class="span4">BDM</th>
<th class="span4">Owed</th>
<th class="span4">Amount</th>
<th class="span2"></th>
</tr>
</thead>
<tbody id="dealerUnpaid" style="display:block; overflow:auto; max-height:400px;">
</tbody>
<tfoot id="dealerUnpaidtot" class="navbar-static-top" style="display:block; margin:0px; cell-spacing:0px; left:0px; font-weight: bold;">
</tfoot>
</table>
It displays the data from the first javascript, but I also have this code from the view it's GET from...
<td class="span4"><input type="text" placeholder="Enter Amount" class="payAmount" data=name="amount" data-id="{{$unpaid->id}}" id="payAmount_{{$unpaid->id}}"></td>
<td class="span2"><input type="button" class="btn pay" value="Pay" data-id="{{$unpaid->id}}"></td>
When I press the Pay button it doesn't do anything :/
Any help to make this work would be nice please.
Thanks guys
If I understand correctly, you're loading your markup (including the .pay element) using AJAX and then attempting to bind something to the .pay element's click event. Since the .pay element doesn't exist in the page at the time you're doing the binding, the binding isn't working. Change your binding from:
$('.pay').click(function(){
to
$(window).on('click', '.pay', function(){
That will attach the binding to the window, which has the effect of working even on elements that are added after the window is loaded.
$(".pay").click(function(){...
Works only on already create elements with class pay, it doesnt work on newly created elements by ajax call.
You can use delegate function to handle newly created elements
$("body").delegate(".pay","click",function(event){
event.preventDefault(); // prevent default handlings
alert("Test");
//do other code...
});

Categories

Resources