Execute DataTables or re-draw tables after ajax - javascript

When user click o a link it gets the ajax executed, when I get from the ajax result is an html which contains div's and tables, actually is just one table... I want to use the library DataTables for this particular result
<html>
<body>
<ul>
<li>Click</li>
</ul>
<div class="results" id="result1"></div>
<script>
$("#link1").on('click', function(e){
e.preventDefault;
$.ajax({
url: 'ajax.php',
data: { id: ids},
dataType: 'html',
type: 'GET',
cache: false,
success: function(data){
$('#result1).html(data);
},
error: function(data){
console.log(data);
}
})
})
</script>
</body>
</html>
So everything the ajax will output is a basic html
<div class="row">
<div class="col-sm-12">
<h4>Some title</h4>
<h5>A sub-title...</h5>
<div class="table-responsive">
<table class="table" id="ajax_table">
<thead>
<tr>
<th>Some 1</th>
<th>Some 2</th>
<th>Some 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>T1</td>
<td>T2</td>
<td>T3</td>
</tr>
// a whole bunch of rows.. about 100...
</tbody>
</table>
</div>
</div>
</div>
So how can I use the DataTables to "re-draw" that table from the ajax?...
Datatables libraries are loaded before anything else alone with a CSS, jquery, bootstraps, etc... I can ask the other guys where the table is formed to add the datatable script
$('#ajax_table').DataTable({
dom: 'Blfrtip',
buttons: [
'csv', 'excel', 'pdf', 'print'
]
});
But then how do I executed since it will came with the html and the script?...

Try to reinitialized datatables after ajax success
$.ajax({
url: 'ajax.php',
data: {
id: ids
},
dataType: 'html',
type: 'GET',
cache: false,
success: function(data) {
$('#result1).html(data);
},
error: function(data) {
console.log(data);
}
})
})
$('#ajax_table').dataTable().fnDestroy();
$('#ajax_table').dataTable({
"aoColumns": [{
"bSortable": false
},
null, null, null, null
]
});

Related

Adding delete button to bootstrapTable in MVC

I have a .Net MVC project that fills a table with data using a bootstrapTable from bootstrap v3. I want to add a delete button to each row.
The bootstrapTable takes json data and loads it. The json is built like this:
public virtual JsonResult Search(FormCollection searchArgument)
{
IEnumerable<MyData> myListData = GetMyListData(searchArgument);
var jsonResult = Json(myListData, JsonRequestBehavior.AllowGet);
return jsonResult;
}
So the jsonResult is just a list of all of my MyData. My view that shows the result looks like this:
#model MyNamespace.Web.Models.MyListViewModel
<div class="col-md-12">
#{
ViewBag.Title = "Index";
Layout = MVC.Shared.Views._Layout;
<div class="row">
<div class="col-md-12">
<form role="form" id="formsearch">
<input id="fromsearch" name="fromsearch" type="hidden" value="true" />
<div class="form-group">
#Html.LabelFor(m => m.Status, "Status:")<br />
#Html.DropDownList("status", new SelectList(Model.Status, "Value", "Key", Model.SelectedStatus), new { #class = "selectButton" })
</div>
<input type="button" id="btnsearch" value="Search" />
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
</tr>
</thead>
</table>
</div>
</div>
}
</div>
<script>
$("#btnsearch").click(function () {
$('#table').bootstrapTable('showLoading');
$.ajax({
type: "POST",
url: "#Url.Action(MVC.MyController.ActionNames.Search, MVC.MyController.Name)",
data: $('#formsearch').serialize(),
dataType: "json",
success: function (data) {
$('#table').bootstrapTable('hideLoading');
$('#table').bootstrapTable({
data: data,
striped: true,
pagination: true,
pageSize: 25,
pageList: [10, 25, 50, 100, 200],
search: false
});
$('#table').bootstrapTable('load', data).on('click-row.bs.table', function (e, row, $element) {
Showdetail(JSON.stringify(row));
});
},
error: function (err) {
console.log(err)
}
});
});
function Showdetail(jsonrow) {
var obj = JSON.parse(jsonrow);
window.location = "#Url.Action(MVC.MyController.ActionNames.ShowMyData, MVC.MyData.Name)?myDataId=" + obj.Id;
}
</script>
#section AddToHead
{
#Styles.Render("~/bundles/bootstrap-table/css")
}
#section scripts
{
#Scripts.Render("~/bundles/bootstrap-table")
}
So the javascript function ("#btnsearch").click gets the json data from public virtual JsonResult Search and sends that to bootstrapTable which loads the data in the table. What I want to do is to add a new header in my table, like this:
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
<th></th>
</tr>
</thead>
</table>
And then in the last column add a delete button that has the id of that row (#Model.Id for instance) so that I can call the controller to delete the row from the database and then reload the table so that the row also disappears from the GUI.
I could easily do it with an ActionLink but since I don't loop through all objects and then draw them out on the page, I can't just add an ActionLink to the page. All the rendering of the rows is done in the bootstrapTable.
I looked at this question and answer and it seemed promising but it's not quite what I'm doing and I can't get my head around what I would need to do to get it working for me: Bootstrap table - dynamic button in row.
According to documantation and examples here:
https://live.bootstrap-table.com/example/column-options/events.html
Add to your scripts:
<script>
var $table = $('#table')
function operateFormatter(value, row, index) {
return [
'<a class="remove" href="javascript:void(0)" title="Remove">',
'<i class="fa fa-trash"></i> Delete',
'</a>'
].join('')
}
window.operateEvents = {
'click .remove': function (e, value, row, index) {
//edit here for ajax request to delete row.id record
$.ajax({
type: "POST",
url: "#Url.Action(MVC.MyController.ActionNames.Delete,MVC.MyController.Name)",
data: {id:row.id},
dataType: "json",
success: function (data) {
//when success remove row
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
})
},
error: function (err) {
console.log(err)
}
});
}
}
</script>
and edit your html table:
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
<th data-field="operate" data-formatter="operateFormatter" data-events="operateEvents">Actions</th> <!--add this col-->
</tr>
</thead>
</table>

JavaScript - jQuery.Tabledit didn't work with specific url

I was trying to intergrate jQuery.Tabledit (https://markcell.github.io/jquery-tabledit/) to my table. While it worked for one table, the other one didn't work. After lots of trial, I found out something weird when changing url.
Basic structure of my table:
index.php
<script type="text/javascript" src="tabledit.js"></script>
<table id="testing">
<thead>
<tr id="head">
<th>id</th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr id="1">
<th>1</th>
<td>a</td>
<td>b</td>
</tr>
<tr id="2">
<th>2</th>
<td>c</td>
<td>d</td>
</tr>
</tbody>
</table>
<?php var_dump($_SESSION); ?>
tabledit.js
$(document).ready(function(){
$('#testing').Tabledit({
columns: {
identifier: [0, 'id'],
editable: [[1, 'Column 1'], [2, 'Column 2']]
},
onSuccess: function(data, textStatus, jqXHR) {
console.log('Success');
},
onFail: function(jqXHR, textStatus, errorThrown) {
console.log('Fail');
},
onAjax: function(action, serialize) {
console.log('onAjax');
console.log(action);
console.log(serialize);
},
hideIdentifier: false,
url: '../../database/test.php',
});
});
test.php
<?php
session_start();
$_SESSION['test'] = 'heya';
?>
Now, if I put the file test.php next to tabledit.js and change url code to
url: 'test.php',
, the session variable won't change, which means test.php isn't running at all.
If I put it to one folder above tabledit.js (ex: project/table/tabledit.js and project/test.php) and change url code to
url: '../test.php',
, it won't work either.
However, if I put it 2 folders above, like this:
url: '../../test.php',
, it works.
Same thing happens with
url: '../../database/test.php',
I had pull an all-nighter for this and still couldn't figure out why. Any suggestion is appreciated.

My Ajax request only sent once

I have an ajax request for getting the purchased list of a user. I thought it was perfectly working because it returns the data that I need. But when I click the other user it seems the ajax request only send a request once. Becuase the data is the same, and when I look at the network tool of chrome, there is no another request was send.
This is my current Ajax request.
var purchased_list;
// $('#student_profile_purchased_item_list_tab').click(function(){
function createTablePurchasedList(id){
console.log("Start, student:"+id);
purchased_list= $('#purchased_item_list_table').DataTable({
// "processing": true,
// "paging": false,
// "ordering": true,
"ajax": {
url:'{{ route("student_item_list") }}?student_id='+id,
cache: true,
dataSrc: "",
},
columnDefs: [
{
className: "dt-center",
targets: [0],
},
],
"columns": [
{
data: "date_purchased"
},
{
data: "product_status_id",
render: function(data, type, row){
switch(data){
case 2:
return 'Purchased';
case 3:
return '<p style="color:red;">Consumed</p>';
case 6:
return '<p style="color:green;">Transferred</p>';
}
}
},
{
data: "name",
render: function(data, type, row){
return data;
}
},
]
});
console.log("End, student:"+id);
}
// });
Tab
<li>Purchased Item List</li>
Datatable
<div class="tab-pane fade in" id="student_profile_purchased_item_list">
<div style="position:relative;">
<div class="other_content_header">
Item List
</div>
</div>
<div class="row">
<div class="col-sm-12">
<table width="100%" class="responsive table table-striped table-bordered table-hover purchase-item-table" id="purchased_item_list_table" style="font-size:12px; text-align:center;">
<thead>
<tr>
<th>Date</th>
<th>Item Status</th>
<th>Product Name</th>
{{-- <th>Quantity</th> --}}
{{-- <th> </th> --}}
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
every time I click a user the console.log result changes, At first I thought the ID is not changing when I click another user. But when I do the console log the result changes.
Hope someone can help me solve my problem.

Ajax Include Data In Dropdown List

Currently i'm retrieve data from api. The data contains id and charity_name. It must be on dropdown list. Currently successful to show the charity name in the dropdown list but stuck on the id. How can i include the id in the option in the dropdown list?
$.ajax({
type: 'GET',
url: 'http://ayambrand-com-my-v1.cloudaccess.host/administrator/index.php?option=com_echarity&format=raw&task=api.get_charities',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('#list').append($('<option>', {
text: element.charity_name
}));
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div>
<form>
<table class="a">
<tr>
<td>
<select id="list">
</select>
</td>
</tr>
</table>
<table class="b">
<tr>
<td>
<span>Content</span>
</td>
</tr>
</table>
</form>
</div>
Can someone point me to the right direction?
Thanks.
Just use value: id in e.g
$('#list').append($('<option>', {
text: element.charity_name,
value: element.id
}));
It will be helpful to you
$(function(){
//place this inside your ajax success
var data=[{id:1,charity_name:"One"},{id:2,charity_name:"two"}];
var html="";
$.each(data, function(index, element) {
html+="<option value="+element.id+">"+element.charity_name+"</option>";
});
$('#list').append(html);
/*$.ajax({
type: 'GET',
url: 'http://ayambrand-com-my-v1.cloudaccess.host/administrator/index.php?option=com_echarity&format=raw&task=api.get_charities',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
}
});*/
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div>
<form>
<table class="a">
<tr>
<td>
<select id="list">
</select>
</td>
</tr>
</table>
<table class="b">
<tr>
<td>
<span>Content</span>
</td>
</tr>
</table>
</form>
</div>

How to refresh ng-repeat table in AngularJS onclick button?

I can not update the value of the fields in the table with ng-repeat in any way onclick of a JS function, not even with a $ scope.apply () or with a timeout.
This is my HTML Code :
<div class="container">
<table class="table" id="table">
<thead class="table-bordered">
<th ng-repeat="(column_name,v) in response[0];">{{column_name}}<br>
<b>Class:</b>
<a ng-click="chooseClass(column_name)" id="{{column_name + 1}}">
{{kls_dict[column_name][0]}}
</a>
<br>
<b>Transfs:</b>
<a ng-click="chooseTrf(column_name)" id="{{column_name + 2}}">
{{kls_transfs[kls_dict[column_name][0]][0]}}
</a>
</th>
</thead>
<tbody>
<tr ng-repeat="row in response">
<td ng-repeat="value in row">{{value}}</td>
</tr>
</tbody>
</table>
</div>
And this is my JS function called in another HTML button component :
$scope.save_params = function (old_transformation, object) {
console.log("Enter save_params");
console.log("trfs", old_transformation)
console.log(object)
console.log('class', $rootScope.old_class)
console.log('columns_name', $rootScope.show_column_name)
to_send = {
'class': $rootScope.old_class,
'column_name': $rootScope.show_column_name,
"trfs": old_transformation,
"params": object
}
$rootScope.spm.close();
$http({
url: "/send_parameters",
method: "POST",
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(to_send)
}).success(function (data) {
console.log(data)
}).error(function () {
console.error('Errore durante invio dei parametri');
$("#warning-alert").text("Errore durante l'invio dei parametri, riprovare o controllare i parametri specificati");
$("#warning-alert").fadeTo(2000, 500).slideUp(500, function () {
$("#warning-alert").slideUp(500);
});
});
};
I have already specify the AngularJS controller. Thanks everyone :)

Categories