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.
Related
Hi guys I have a problem when I'm using jQuery datatable. After Datatable is loaded by submitting an ID to the server, and then server response with the data that I render then into DataTable. In that DataTable I want to make multiple row selection and the values that I want to push into array are for example all the values of first column. My code below is everything that I have created now.
The HTML Code:
<form name="search_form_order" id="search_form_order" novalidate="">
<input type="text" name='login_id' id="login_id" class='form-control'>
<button type="submit" name="search" id="search">Search</button>
</form>
<table id="orders_table" width='100%'>
<thead>
<tr>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tr>
</thead>
<tfoot>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tfoot>
</table>
jQuery Code:
//This is the part where user submit the id parameter
$('#search_form_order').on('submit', function(event) {
event.preventDefault();
var id = $('#login_id').val();
$('#orders_table').DataTable().destroy();
loadOrdersTable(id);
});
//This is the function
function loadOrdersTable (id) {
table=$('#orders_table').DataTable({
responsive: true,
processing: true,
serverSide: false,
lengthMenu: [[100, -1], [100, "All"]],
"ajax": {
url: "/list_orders.php",
type:"POST",
dataSrc: "",
data: {login_id:id}
},
columns: [
{data: 'login_id', name: 'login_id'},
{data: 'order_id', name: 'order_id'},
{data: 'comment', name: 'comment'},
{data: 'actions', name: 'actions'}
]
});
}
Until here everything works perfectly, but when I want to select the the order_id-s of each row, the below jQuery code do not work:
var dataArr = [];
$('#orders_table tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
});
console.log(dataArr);
This I'm using because I want to populate this array, to make bulk edit or bulk delete of all selected rows. On console it is displayed only this '[]', as output since onlcick event do not get the value from table rows.
Thank you!
your mistake is that you have your console.log outside of the event handler. That means that it's executed when the page is loaded and thus the array is empty.
If you move that inside your event handler (1 before) you'll se that everytime you click, the ID is pushed to the array and then shown at console.
Here is a working snippet:
PD: Note that everytime you click on one row the ID will be added to the array causing possible duplications, meanwhile the toggle will.. toggle, probably causing unexpected behaviours. You should need to add extra logic to avoid that
var dataArr = [];
$('#orders_table tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
console.log(dataArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="orders_table" width='100%'>
<thead>
<tr>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>login_id</td>
<td>order_id</td>
<td>comment</td>
<td>actions</td>
</tr>
</tbody>
<tfoot>
<th>Login ID</th>
<th>Order ID</th>
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tfoot>
</table>
I am having trouble getting Datables to work.
No-matter what I try, I am getting the issue that there is no data.
The message exactly is: "No matching records found".
I am using the correct format found here on the official website but it doesn't seem to want to load.
I am not using MYSQL so haven't include any SPP, but am just returning the array of address's inside an array then encoding it in JSON.
In my frontend file, I am trying to load all address's from a certain router:
<script type="text/javascript">
$(document).ready(function() {
$('#table').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "<?=url('database/addresses');?>",
"dataSrc": "",
},
'columnDefs': [{
'targets': 1,
'checkboxes': {
'selectRow': true
}
}],
'select': {
'style': 'multi',
'selector': 'td:first-child'
},
'order': [[5, 'desc']],
"columns": [
{ "data": "id" },
{ "data": "id" },
{ "data": "input_address" },
{ "data": "destination_address" },
{ "data": "callback_url" },
{ "data": "dateCreated.date" },
{ "data": "id" }
],
'colReorder': true
});
} );
</script>
My html table:
<form method="post" id="deleteMulti" class="ajax-multi" action="<?=url('XhPCrvFtQuE7gPP6/addresses/delete/selected');?>">
<?= csrf() ?>
<div class="row">
<div class="col-xxl-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Addresses [ <?=$count;?> ]</h4>
<div class="right fr">
<button class="btn tooltip" style="display: inline;" name="deleteSelected" title="Delete Selected Addresses"><i class="fa fa-trash" style="color: black;"></i></button>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="table" class="display">
<thead>
<tr>
<th>#</th>
<th><input type="checkbox" class="" id="checkAl"></th>
<th>Input Address</th>
<th>Output Address</th>
<th>Callback Url</th>
<th>Created</th>
<th><i class="bi bi-archive-fill"></i></th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
**And in my database/addresses to load the database content:**
// This is used for when we need to load more address's to the admins /addresses page
public function getAddresses() {
define('PAGE_NAME', 'Admin Addresses');
// Skip 100 as we will start from the 100th row
// We set the limit to 100 in Admin page so the page loads 100 much faster
// We will push more and more using this function inside here for when they click load more
$addresses = \r\table('addresses')->orderBy(array('index' => \r\desc('dateCreated')))->skip(100)->limit(100)->run($this->conn);
$addresses = $addresses->toArray();
$count = count($addresses);
$theArr = array();
foreach ($addresses as $address) {
$theArr[] = $address;
}
$final = array(
'draw' => 1,
'recordsTotal' => $count,
'recordsFiltered' => $count,
'data' => array_values($theArr)
);
if($count > 0) {
echo json_encode($final, JSON_FORCE_OBJECT);
} else {
return false;
}
}
My issue is that it keeps showing me:
No matching records found eventhough I do have over 4k records in there.
Take a look at this picture here
Take a look at the format of the json returned from my getAddresses():
here
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>
I am using the dynatable.com plugin to create a table of of schools that are stored in our database. The table can be filtered so does not always show the total number of schools. We do not display a 'number of pupils' column but are trying to show a 'total number of pupils' summary at the bottom of the table.
html on the page is as follows:
<table id="dynatable">
<thead>
<tr>
<th data-dynatable-column="id">ID</th>
<th data-dynatable-column="schoolName">School Name</th>
<th data-dynatable-column="contactName">Contact Name</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="3"><span id="numPupils"></span> Pupils</td>
</tr>
</tfoot>
</table>
Followed by the JS:
<script>
$('#dynatable').dynatable({
dataset: {
ajax: true,
ajaxUrl: '/my/json/page.json',
ajaxOnLoad: true,
records: []
}
});
</script>
And a sample of the JSON retrieved (note the additional totalNumPupils field at the bottom):
{
"records": [
{
"id": "1",
"schoolName": "ABC School",
"contactName": "Terry"
},
{
"id": "17",
"schoolName": "DEF School",
"contactName": "Claire"
},
{
"id": "45",
"schoolName": "GHI School",
"contactName": "Barry"
}
],
"queryRecordCount": 3,
"totalRecordCount": 450,
"totalNumPupils": 794
}
I am trying to establish if there is a way to access the responseJSON.totalNumPupils that is requested by dynatable's ajax call or whether I would have to perform my own ajax call, ascertain the number of pupils, then pass in the JSON to the dynatable function afterwards?
Please see the code snippet. You can use normal AJAX to get the JSON payload, then populate the dynatable with the data from the AJAX response, while simultaneously accessing the unique totalNumPupils property.
$('#dynatable').dynatable({
dataset: {
ajax: true,
ajaxUrl: 'https://api.myjson.com/bins/1ezw8l',
ajaxOnLoad: true,
records: []
}
});
$.ajax({
url: 'https://api.myjson.com/bins/1ezw8l',
success: function(data) {
$('#dynatable').dynatable({
dataset: {
ajax: false,
records: data
}
});
$('#numPupils').text("Total Pupils: " + data.totalNumPupils);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.css" rel="stylesheet" />
<table id="dynatable">
<thead>
<tr>
<th data-dynatable-column="id">ID</th>
<th data-dynatable-column="schoolName">School Name</th>
<th data-dynatable-column="contactName">Contact Name</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="3"><span id="numPupils"></span> Pupils</td>
</tr>
</tfoot>
</table>
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
]
});