I have a data table in my page with the status column and view details column. after clicking view details it will pop up a modal, the modal contains a dropdown for status that when changed a certain value in the database will change. However after closing the modal the value in the datatable doesn't change. How can I reload the data table without reinitializing it, or how to get the column & row that i clicked so that I can change the value of the certain column & row. I have this code for initializing the datatable on doc.ready
function createTable(data){
for (i in data){
var message = "<tr>";
var statusHolder = "";
if(data[i].status == "open"){
statusHolder = "Open";
} else if (data[i].status == "resolved"){
statusHolder = "Resolved";
} else {
statusHolder = "Closed";
}
var id = data[i].id;
message+= "<td>" + statusHolder + "</td>";
message+= "<td><input id = 'ticketId' type ='hidden' value = " + data[i].id +" /><input type = 'hidden' id = 'support-type-name' value = 'call-back'/><a href='javascript:retrieveCommentsInfo(" + data[i].id +")' id='view-ticket-info'>" + " View details" + "</span></td>";
message+= "<td>" + data[i].id + "</td>";
$("#callback-request-body").append(message);
}
$("#callback-request-table").dataTable({
"columnDefs": [ {"visible": false, "targets": [6]},
]
});
}
Answered! So I used this created a function the will reintialize datatables.
function reInitializeDataTables(){
callbackTable.destroy();
$("#callback-request-body").empty();
retrieveCallBackRequests();
contactUsTable.destroy();
$("#contactus-table-body").empty();
retrieveContactUsMessages();
}
I'll just use .destroy() function to the datatable and then remove all contents of the body of the data table.
Related
I am having trouble getting my button to click after an ajax call. It works fine before the call. However, when i perform a search and return the data from php, the click event stops working.
I have tried the .on event but this just display the form and not the values. I would be grateful if someone could check my code and see where I am going wrong.
I am aware that the element needs to be in the page and I assumed that after he ajax call the dom would contain the element. Obvously i was wrong.
Many thanks
Order of clicks.
1) page load, .edit click works fine.
2) perform search from #btn-search. Pagintes the table but .edit click is no longer firing.
js code
Get inital values from row. works fine on first click. Not after ajax call to display search results
$(function() {
$('.edit').click(function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
service = currentRow.find("td:eq(1)").html();
activity = currentRow.find("td:eq(2)").html();
dept = currentRow.find("td:eq(3)").html();
company = currentRow.find("td:eq(4)").html();
address = currentRow.find("td:eq(5)").html();
user = currentRow.find("td:eq(6)").html();
item = currentRow.find("td:eq(7)").html();
date = currentRow.find("td:eq(8)").html();
var data = id + "\n" + service + "\n" + activity + "\n" + dept + "\n" + company + "\n" + address + "\n" + user + "\n" + item + "\n" + date;
$("#editForm").dialog("open");
$("#id").val(id);
$("#service").val(service);
$("#activity").val(activity);
$("#dept").val(dept);
$("#company").val(company);
$("#address").val(address);
$("#user").val(user);
$("#item").val(item);
$("#datetimepicker").val(date);
});
});
php backend
<?php
if ($_POST['search1'] == '') {
echo 'enter a search term';
exit;
} else {
$search = $_POST['search1'];
$sqlsrch = mysqli_query($conn, "select * from act where item like '%$search%'");
$numsrch = mysqli_num_rows($sqlsrch);
if ($numsrch == 0) {
// what to do if no results found
echo 'No Results Found';
} else {
while ($rowsrch = mysqli_fetch_array($sqlsrch)) {
$id = $rowsrch['id'];
$service = $rowsrch['service'];
$activity = $rowsrch['activity'];
$dept = $rowsrch['department'];
$company = $rowsrch['company'];
$address = $rowsrch['address'];
$user = $rowsrch['user'];
$box = $rowsrch['item'];
$date = $rowsrch['date'];
$date = date('d/m/Y h:i:s', strtotime($date));
$edit = "<button type='button' class='btn btn-primary edit'>Edit</button>";
$action = "<button type='button' class='btn btn-success action'>Action</button>";
$delete = "<button type='button' class='btn btn-danger delete'>Delete</button>";
// Now for each looped row
echo "<tr><td>" . $id . "</td><td>" . $service . "</td><td>" . $activity . "</td><td>" . $dept . "</td><td>" . $company . "</td><td>" . $address . "</td><td>" . $user . "</td><td>" . $box . "</td><td>" . $date . "</td><td>" . $edit . ' ' . $action . ' ' . $delete . "</td></tr>";
} // End our scale while loop
}
}
?>
jquery search click event
$(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
var search = $("#search").val();
$.ajax({
url: "tabletestajax.php",
method: 'POST',
data: {
search1: search
},
success: function(data) {
$("#search").val('');
$(".paginated tbody").empty();
var result = $.trim(data);
if (result === "enter a search term") {
$("input[name='search']").val(result).css({
'color': 'red'
});
return false;
} else if (result === "No Results Found") {
$(".paginated tbody").html('<div>' + result + '</div>');
return false;
} else {
$(".paginated tbody").html(result);
}
}
});
});
});
Probably you need event delegation
$(document).on('click', '.edit', function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
.
.
}
Resource
Event delegation .on()
I am filling a table with some data that I get from firebase database, and for that I am using append()
$("#table_body").append("<tr><td>" + nome + "</td>" +
"<td>" + marca + "</td>" +
"<td>" + modelo + "</td>" +
"<td>" + setor + "</td>" +
"<td>" + responsavel + "</td>" +
"<td><div buttons>"+
"<button>Delete</button>"+" "+
"<button>Edit</button>"+
"</div></td></tr>");
But then, I don't know how to use the "Remove" and "Edit" buttons on each row of the table, shouldn't I have the ID of each row? But then, how do I get the ID of each row if the rows are added dynamically?
You have an object ID from your data model ... add that as an attribute to the row.
Then use a traverse to closest() row to isolate instances
Following assumes a button with class added :
<tr data-id="idFromFirebaseObject">
....
<button class="delete-btn">Delete</button>
Then use event delegation to account for elements that don't yet exist at run time
$("#table_body").on('click','.delete-btn', function(e){
// "this" is element event occurred on
var $row = $(this).closest('tr'),
rowId = $row.data('id');
// do your thing with FB then in success callback remove row
....
$row.remove();
})
I have a table with many checkboxes which is generated with Ajax :
$.ajax({
type: "GET",
url: "jsonDevisUtilisateur.php?ra=" + $('#ra').val(),
success: function(data) {
var table = "<table class='dvs'><tr><td>Numéro</td><td>Client</td><td>Site</td><td>Libellé</td><td>Statut</td><td></td></tr>"
for (var i = 0; i < data.length; i++) {
table += "<tr><td>" + data[i].numDevis + "</td>";
table += "<td>" + data[i].client + "</td>";
table += "<td>" + data[i].site + "</td>";
table += "<td>" + data[i].libelle + "</td>";
table += "<td>" + data[i].statut + "</td>";
table += "<td><input type='checkbox' class='box' value='" + data[i].id + "' name='box[]'></td></tr>"
}
table += "</table>";
document.getElementById('devis').innerHTML = table + "<br/><br/>";
}
});
This part is working well !
The problem is when I'm trying to integrate a "select all" button.
My Javascript for it :
$(document).ready(function() {
$("#selectall").on("change", function(e) {
$("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});
});
When my select all checkbox : <input type='checkbox' id='selectall' name='selectall'> is created on the same time than my HTML, it works.
But if I create my <input type='checkbox' id='selectall' name='selectall'> in my TABLE with my ajax function, it doesn't work, and nothing happens.
I'm pretty sure it is because the event is set to "selectall" at the load of the page but it doesn't exist yet and it doesn't look for it later.
What would be the solution ? Thanks for help
You can use event delegation as follow:
$('#devis').on("change", "#selectall", function(e) {
$("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});
You are right in your thinking :
If your selectall checkbox is created after the document ready code execution, jquery can't find it (as it's not created yet).
I won't recommand using the live function as it is deprecated and can be removed in futur version of jquery.
You can still use the on function but with a little modification :
$("#devis").on("change", "#selectall",function(e) {
Note that #mycontainer MUST exist on document load.
If you can't place a container, this will always work :
$("body").on("change", "#selectall",function(e) {
I am working on a script that copies a row ID from one table and creates a new table on the page with all rows that have been selected via checkbox in order to create a comparison table of selected results and I've run into an issue with the synergy between two of my ajax calls.
When the following row is created in the original table, the class that is assigned to the <a> element of that row triggers an ajax call which then populates a modal that shows up on the page with additional information.
This is the line
echo "<td><a id='$id' data-toggle='modal' href='#provmodal' class='push'>".$results['provider_name']."</a>";
When the modal is triggered this way, the information populates just fine.
Now, within the script that populates the new table, I make a call to another separate script which re queries the selected row ids and sets the html.
Here is that portion of the script :
$('.compareCheck:checked').each(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'compare.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
dataType: "json",
success : function(data){
var row = "<tr class='removeRow'>";
row += "<td>" + data.provider_num + "</td>";
//HERE IS WHERE THE RE-CREATION OF THE MODAL CALL GOES \/
row += "<td><a id='" + ele_id + "' data-toggle='modal' href='#provmodal' class='push'>" + data.provider_name + "</a></td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['233_net_charity_care']) + "</td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['291_cost_of_non_mcr_bad_debts']) + "</td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['301_cost_of_uncomp_care']) + "</td>";
row += "<td style='text-align:right;'>" + ((data['233_net_charity_care']/data['301_cost_of_uncomp_care'])*100).toFixed(1) + "%</td>";
row += "<td style='text-align:right;'>" + ((data['291_cost_of_non_mcr_bad_debts']/data['301_cost_of_uncomp_care'])*100).toFixed(1) + "%</td>";
row += "</tr>";
$("#compareTable > tbody").append(row);
}
});
});
As you can see in my current implementation I am using the ele_id var, but I have also tried things like data.id and data['id']. All of which trigger the modal but produce no results from the php script.
Here are my two php scripts:
Script A: Populating the modal - (modalquery.php)
<?php
require_once("link_costreport_2013.php");
$id = $_POST['post_id'];
$modalquery = $link->prepare("SELECT * FROM s10 WHERE id = :id");
$modalquery->bindParam(':id', $id, PDO::PARAM_INT);
$modalquery->execute();
$modalresults = $modalquery->fetch();
print_r("<h4>State: ".$modalresults['state']."</h4>");
print_r("<h4>City: ".$modalresults['city']."</h4>");
print_r("<h4>Street: ".$modalresults['street']."</h4>");
print_r("<h4>Zip: ".$modalresults['zip']."</h4>");
print_r("<h4>County: ".$modalresults['county']."</h4>");
?>
and script B - The script that turns the re-query into values for the new comparison table (compare.php)
<?php
include_once('functions.php');
include_once('link_costreport_2013.php');
if(isset($_POST['post_id'])){
$id = $_POST['post_id'];
}
$query = $link->prepare("SELECT *
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
echo json_encode($results);
?>
also in case it helps, here is my script for turning the .push class into a trigger for the ajax call which returns the modal content.
$(function(){
$('.push').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'modalquery.php', // in here you should put your query
data : 'post_id='+ ele_id, // here you pass your id via ajax .
// in php you should use $_POST['post_id'] to get this value
success : function(r)
{
// now you can show output in your modal
$("#provmodal .modal-body").html(r).promise().done(function(){
$("#provmodal").modal('show');
});
}
});
});
});
I'm new to using ajax and jquery in this fashion so any insight at all would be excellent.
thanks in advance
:EDIT: Here is the output from json_encode($results) when ID = 1
{"id":"1","report_record_num":"548598","provider_num":"381301","provider_name":"COTTAGE GROVE COMMUNITY HOSPITAL","street":"1515 VILLAGE DRIVE","city":"COTTAGE GROVE","county":"LANE","state":"OR","zip":"97424-9700","cbsa":"21660","urban_or_rural":"Rural","ownership_type":"Voluntary, Nonprofit, Church","divider":"","divider2":"","1_cost_to_charge_ratio":"0.703459","2_net_rev_from_mcd":"3920096","3_recieve_sup_mcd_payments":"Y","4_include_if_yes":"N","5_dsh_or_sup_payments":"84890","6_medicaid_charges":"6192717","7_medicaid_cost":"4356323","8_dif_net_rev_and_cost":"351337","9_schip_net_rev":"0","10_stnd_alone_schip_charges":"0","11_stnd_alone_schip_cost":"0","12_diff_schip_rev_and_cost":"0","13_net_rev_from_state_local":"0","14_charge_under_state_law":"0","15_state_local_program_cost":"0","16_dif_between_net_rev_and_cost":"0","17_private_grants_and_donations":"6886","18_gov_grants":"0","19_tot_unreim_cost_mcd_schip_gov":"351337","201_tot_init_charity_for_uninsured":"593922","202_tot_init_charity_for_insured":"1072203","203_tot_init_charity_all":"1666125","211_cost_of_init_charity":"417800","212_cost_of_init_charity":"754251","213_cost_of_init_charity":"1172051","221_partial_pmt_charity_pat":"4385","222_partial_pmt_charity_pat":"8868","223_partial_pmt_charity_pat":"13253","231_net_charity_care":"413415","232_net_charity_care":"745383","233_net_charity_care":"1158798","241_charges_beyond_los_inc":"N","251_charges_beyond_los_lim":"0","261_total_bed_debts":"0","271_medicare_bad_debts":"79275","281_non_medicare_bad_debts":"-79275","291_cost_of_non_mcr_bad_debts":"-55767","301_cost_of_uncomp_care":"1103031","311_cost_of_unreim_and_uncomp":"1454368"}
:EDIT2: Ok, so I went back and took some pics of what is happening. Somehow my modal text is not appearing in the second table <a class="push"> element. Here are the pics:
!(http://imgur.com/xgsOzSy) - This is in the first table
!(http://imgur.com/uSsI3DM) - This is what happens in the second when the same link is pressed. I believe it's not triggering the ajax .push call.
Try changing:
$(document).on('click','.push',function(){
For:
$('.push').on('click', function(){
In the first case the event handler is added to every element with the "push" class that is present in the DOM at the moment of the execution of the "click" function. The second case, the one wich uses the "on" function, it adds the event handler to the elements already present and those which are not yet in the DOM, those which you create after the execution of the adition like the ones you add to the table.
Wish i make my self clear, i am trying to improve my english.
can anyone help please. I have a form generated dynamically, when it is submitted it should send values to a function and add them back to a database. I'm having real problems getting this to work, it seems simple: 1. Form --> 2. submit received --> 3. update function. The code is below:
Dynamically generated form:
function renderResults(tx, rs) {
e = $('#status');
e.html("");
for(var i=0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input value=\"" + r.name + "\" name=\"name\" />" +
"<input value=\"" + r.amount + "\" name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});
}
}
Handles the form submit and passes to function:
$('#theform').submit(function() {
updateRecord($('#thename').val(), $('#theamount').val());
});
Function to set values:
function updateRecord(id, name, amount) {
db.transaction(function(tx) {
tx.executeSql('UPDATE groupOne SET (name, amount) VALUES (?, ?) WHERE id=?', [name, amount, id], renderRecords);
});
}
The DB update code has the id set to 4 as a test just to see if anything happens to row 4, i've been fiddling with this line for ages to get it to work. If i set it to:
tx.executeSql('UPDATE groupOne SET name = 4, amount = 5 WHERE id=?', [id], renderRecords);
it will work with set values, but can someone help me get the form values into it please.
You are missing the row id in your jQuery selector. You are passing:
$('#thename').val();
But your field has an id of "thename" + r["id"]:
'<input type="text" ... id="thename' + r['id'] + '" ...>'
You need to get your value by passing the full input id.
$("#thename" + rowId).val();
Edit: Looking more closely at your code, I notice you are creating multiple forms with the same id, which is invalid html. I see now that you've got one form per record. Good, just lose the id from the form and its inputs. Instead, use names for the inputs.
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input name=\"name\" />" +
"<input name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});