Hi I am wondering if it's possible to do something like selecting a row within a datatable and have a button "delete" with a method in the controller.
My delete button is to remove the row from the database itself and refresh the page.
This is what my view contains:
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#datatables').DataTable();
});
</script>
<table id= "datatables" class = "table">
<thead>
<tr>
<th> Patient Name </th>
<th> Patient`enter code here` ID </th>
</tr>
</thead>
<tbody class = "list">
<?php foreach ($patients as $patient): ?>
<tr>
<td><?=$patient->first_name ?></td>
<td><?=$patient->patientID ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
(delete button)
echo anchor('something/delete', 'Delete', 'class= "some class"');
What i want to do is:
Get the id of the selected row in the datatable and pass it to another page in a controller for processing.
Is that possible?
since you are using DataTables plugin. when defining your columns, add a column for checkboxes, like so:
{
"data": null,
"defaultContent": "",
'class':'user_chkbox',
"searchable": false,
"render": function ( data, type, full, meta ) {
var checkbox = "<input type='checkbox' name='user_ids[]' value='" + data.id + "' />";
return checkbox ;
}
},
you can get the list of id's to delete by accessing the 'user_ids' post data.
$user_ids = $this->input->post('user_ids');
you can then in your submit handler function:
$this->db->where_in('id',$user_ids);
$this->db->delete('user_table');
Related
I am creating an inventory control system for my sales. i can serialize complete table successfully i have one problem i have sell_price column in in table, retail price column is not there in the table.how can send the retail price to the php page.because i need to calculating profit at end the day sales. i am sending all record to loading_add.php page through ajex. what i tried so far i wrote it below. how to send retail_price in to loading_add.php page.
retail_price : retail_price
var table_data = [];
$('#product_list tbody tr').each(function(row,tr)
{
var sub = {
'product_id' : $(tr).find('td:eq(1)').text(),
'cat_id' : $(tr).find('td:eq(2)').text(),
'product_name' : $(tr).find('td:eq(3)').text(),
retail_price : retail_price
'sell_price' : $(tr).find('td:eq(4)').text(),
'qty' : $(tr).find('td:eq(5)').text(),
'total_cost' : $(tr).find('td:eq(6)').text(),
};
table_data.push(sub);
});
$.ajax({
type : "POST",
url: '../php/product/loading_add.php',
dataType: 'JSON',
data: {data:table_data},
One way is to take hidden input if you are not want to display the data to user still you needs it.
for example, in your product listing table, you can take hidden input of retail price as you need it but dont have to display it to users.
so after executing mysql select query you can fetch data in your table as:
<table id="product_list" class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Category</th>
<th>product Name</th>
<th>price</th>
<th>quantity</th>
<th>total</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $row){ ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['cat_id']; ?></td>
<td><?php echo $row['product_name'] ?></td>
<!-- below in sell price td we will take hidden input for retail price -->
<td><input type="hidden" class="retail_price" value="<?php echo $row['retail_price'] ?>"><?php echo $row['sell_price'] ?></td>
<td><?php echo $row['quantity'] ?></td>
<td><?php echo $row['total_cost']; //or price * quantity ?></td>
</tr>
<?php } ?>
</tbody>
</table>
And in your script you have mistaken as $(tr).find('td:eq(1)').text(),
if you want to fetch first td then you should use $(tr).find('td:eq(0)').text() because here td is array of elements and in array index always start with 0.
so your script should be as:
$(function () {
var table_data = [];
$('#product_list tbody tr').each(function (row, tr)
{
var sub =
{
'product_id': $(tr).find('td:eq(0)').text(),
'cat_id': $(tr).find('td:eq(1)').text(),
'product_name': $(tr).find('td:eq(2)').text(),
'sell_price': $(tr).find('td:eq(3)').text(),
'retail_price': $(tr).find('td:eq(3)').find('.retail_price').val(),
'qty': $(tr).find('td:eq(4)').text(),
'total_cost': $(tr).find('td:eq(5)').text(),
};
table_data.push(sub);
});
//here you can fire ajax request for adding record
});
Another way is to take data attribute for your needed value
in same example as above you can take data attribute in your td as
<td data-retail_price="<?php echo $row['retail_price'] ?>"><?php echo $row['sell_price'] ?></td>
and in your script you can get data attribute's value as in same script as above:
'retail_price': $(tr).find('td:eq(3)').data('retail_price'),
I have displayed all the student's name in table format through ajax. Now I want to associate a form input field to each student so that I can insert his marks and store it in database? How can I achieve this?
Below is my code..
<script type="text/javascript">
function select_std() {
var ali = $('#class_std').val();
$('#std_name').html('');
$.ajax({
url: "<?php echo base_url().'admin/test/'?>" + ali,
type: "GET",
success: function(res) {
$('#myTable tbody').append(res);
}
});
}
</script>
and my controller :
public function test($id=''){
$table='students';
$columns=array('*');
$where=array('c_id'=>$id);
$data['rcd']= $this->Crud->get_records($table, $columns, $where)->result();
foreach ($data['rcd'] as $value) {
$output = "<tr><td>".$value->Name."</td><td>90</td><td>very good<td></tr>";
echo $output;
}
}
This is my table format in which I have showed all the student's names in the first <td> through ajax from database. and I want to make the second <td> as input field to store his marks in database.
<table cellpadding="1" cellspacing="1" id="myTable" class="table table-boardered table-responsive" id="example2">
<thead>
<th width="20px;">Name</th>
<th>Marks obtained(100)</th>
<th>comments</th>
</thead>
<tbody id="std_name">
</tbody>
</table>
You should put a form on the table/your loop so that every student has a designated input field then if you want to make an action to a specific student get the ID of the specific student then inserts it to the DB. (get(id) = idfromdb).
<?php foreach ($data['rcd'] as $value) { ?>
<tr><td><?php $value->Name ?></td><td>90</td><td>very good<td></tr>
<tr><td>
<input field here>
<input button value=$value[id]>
</td></tr> <?php } ?>
then in the next page or the same page its up to you:
<?php if(isset($_POST['button name'])){
$id = $_POST[button name];
insert your data to your db where $id = idfromdb }?>
ahaha sorry dude I forgot php. :(
I am fetching data from database in a table.Now i want to edit particular field in a row of the table and save that value into MySQL.
This is my complete code for displaying data in table and editing. Here i want to edit the status. It is editable but after editing how to get the value from the table and update that value to MySQL.
<?php
include "config.php";
$sql = "select * from d_jobs where Status ='drafted' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
//echo $count;
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
$("document").ready(function(){
$('#sdata').click(function(){
var myTxt = $(('.status')+[i]).html();
console.log(myTxt);
var id = $(('.status')+[i]).attr('id');
console.log(id);
}
/* $.ajax({
type: 'post',
url: 'job_field_edit.php',
data: 'varname=' +myTxt
}); */
});
});
</script>
</head>
<body>
<table border="2" align="center">
<thead>
<tr>
<th>Job Name</th>
<th>Builder</th>
<th>Job Type</th>
<th>Status</th>
<th>Effective Date Start</th>
<th>Estimated completion date</th>
<th>Job Gal Glag</th>
<th>Take List Flag</th>
<th>Planner</th>
<th>Project Manager</th>
<th>Hand Over</th>
<th>Other Comments</th>
</tr>
</thead>
<tbody>
<?php
if( $count ==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysqli_fetch_array($result)){
echo "<tr><td>{$row['JOB_NAME']}</td>
<td>{$row['BUILDER']}</td>
<td>{$row['JOB_TYPE']}</td>
<td contenteditable='true' id='{$row['JOB_ID']}' class='status[{$row['JOB_ID']}]'>{$row['status']}</td>
<td>{$row['EFFECTIVE_START_DATE']}</td>
<td>{$row['ESTIMATED_COMPLETION_DATE']}</td>
<td>{$row['JOB_GAL_FLAG']}</td>
<td>{$row['JOB_TAKE_LIST_FLAG']}</td>
<td>{$row['Planner']}</td>
<td>{$row['Project_Manager']}</td>
<td>{$row['Handover']}</td>
<td>{$row['Comments']}</td>
<td><input name='need_delete[{$row['JOB_ID']}]' type='checkbox' id='checkbox[{$row['JOB_ID']}]' value='{$row['JOB_ID']}'></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<input id="sdata" type="button" value="Send Data" />
</body>
</html>
<?php
mysqli_close($conn);
?>
There's a number of ways to approach this. One is to dispense with the manual Send Data button and allow javascript to respond automatically to users' contenteditable edits.
Unfortunately, contenteditable elements don't fire a change event but they do fire a blur event, from which a change event can be triggered.
First, build your contenteditable elements like this :
<td contenteditable=\"true\" class=\"status\" data-job-id=\"{$row['JOB_ID']}\">{$row['status']}</td>
Then, for each contenteditable element, attach a blur handler, and initialize a data-value attribute equal to innerText.
$('[contenteditable]').on('blur', function(e) {
var self = $(this);
if(self.text() !== self.data('value')) {
self.trigger('change');
}
self.data('value', self.text());
}).each(function() {
$(this).data('value', $(this).text()); // equivaluent to data-value="{$row['status']}".
});
Thus you can have contenteditable elements that mimic, at least in part, HTML input elements.
So now you can attach a change handler as you would for a standard HTML input element.
$(".status").on('change', function(e) {
var job_id = $(this).data('jobId');
var old value = $(this).data('value');
var current value = $(this).text(); // in this regard, <input> is not mimicked. For a genuine <input> we would write `$(this).val()`.
// here, perform ajax to keep server-side up to date.
});
DEMO
Note: This approach is slightly over-the-top when [contenteditable] and .status are virtual synonyms for each other. However, in the general case where there might be several different classes of contenteditable element, then you would likely avoid much repetition of code.
I'm very new to php and have been given the task to update the table in the database when user select the check box and then edit the information in the text box. I'm able to pull the information from database and display it on the screen, however I'm not too sure how to update the database when user selects the checkbox and update the field
Here is what I want to achieve:
1) On clicking the checkbox, the row gets editable.
2) After updating the field value, and clicking button "update", the value gets updated in the d/b
<div class="table-responsive">
<table class="table table-condensed">
<thead>
<tr>
<th width="20%">Field Name</th>
<th width="52%">Field Text</th>
<th width="32%">Select to Update</th>
</tr>
</thead>
<tbody>
<?php
if($table = true)
{
while($row = $result->fetch_assoc())
{
$fieldName[] = $row['fieldName'];
$fieldText[] = $row['fieldText'];
$fieldID[] = $row['ID'];
echo "<tr>";
echo "<td>".$row['fieldName']."</td>";
echo "<td>".$row['fieldText']."</td>";
echo "<td>"."<input type= 'checkbox' value='{$row['ID']}', name = ID[]>"."</td>";
echo "</tr>";
}
}
else
{echo "No results found";}
?>
</table>
</div>
Not sure how to proceed further. After checking forums, I found that Jquery is the way to go, but not sure how to make the field updatable.
Please note that I haven't provided the code for the "Update" functionality.
Sorry, i am not good in jquery. But i think for this u could use
$('.your-check-box').on('change', function() {
if(this.checked)
{
//change text on inputs
}
else {
//change inputs on text
}
});
this is quick example:
http://jsfiddle.net/qr4ova98/
For DB update u need to send ajax with data on event.
I have an html table, and on each row, i would like to add a delete button.
When the user clicks on it, I would like to do two things:
1) remove the row from the table.
2) extract data from the row that was removed - a particular cell, and then make an ajax call using this value to a function that will remove the record from the database. The function returns a fresh list of items, which i will then use to redisplay the same table.
I found the following post from someone else on stackoverflow:
How to remove current row from table in jQuery?
So I guess that addresses point number one. But I don't know how to modify the code in the selected answer of the post to allow for grabbing the id value in the row, and then making an ajax call.
<table class="table table-bordered table-striped" id="databaserecords">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Status</th>
<th>Voice</th>
<th>Jumbo</th>
<th>Mode</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php foreach ($dblist as $record): ?>
<tr>
<td class ='recordId'><?php echo $record['Id'] ?></td>
<td class ='recordName'><?php echo $record['Name'] ?></td>
<td><?php echo $record['Status'] ?></td>
<td><?php echo $record['Voice'] ?></td>
<td><?php echo $record['Jumbo'] ?></td>
<td class='recordmode'><?php echo $record['Mode'] ?></td>
<td><button id="deleteRecord">Delete Record</button></td>
</tr>
<?php endforeach ?>
<script>
$('#deleteRecord').live('click', function() {
//get a count of all records. only allowed to delete if you have more than one record.
var recCount = $('#databaserecords tbody tr').length;
if (recCount > 1)
{
$thevalueIwanttoSave = $(this).closest('recordId').val();
alert($thevalueIwanttoSave);
}
});
</script>
Right now, the alert always says that my variable is undefined.
Can you point me in the right direction? I do know how to code an ajax call... I think I just need help with grabbing the value from the table.
Thanks.
You selector is not correct.
$thevalueIwanttoSave = $(this).parent().siblings('.recordId').text();
closest selects the closest parent of the element(recordId is not parent/grandparent or.. of your button element) and you have also missed a . for class selector. val is used for getting/setting values of form elements, for td elements you should use text or html method. Also note that IDs must be unique(you can use classes instead) and live method is deprecated, you can use on method.
$('#databaserecords').on('click', '.deleteRecord', function() {
var recCount = $('#databaserecords tbody tr').length;
if (recCount > 1) {
var text = $(this).parent().siblings('.recordId').text();
alert(text);
// $(this).closest('tr').remove()
}
});
siblings()
parent()
closest()
text()
on()
$thevalueIwanttoSave = $(this).parent('tr').find('.recordId').text();
it should be .recordId, not recordId
$thevalueIwanttoSave = $(this).closest('.recordId').val();
alert($thevalueIwanttoSave);
Add the ID in an attribute on your delete button and you can just get it via jQuery.
in your php loop:
<button class="deleteRecord" recordID="<?php echo $record['Id'] ?>">Delete Record</button>
in JQuery on
$(".deleteRecord").click(function() {
var id = $(this).attr("recordID");
...
});
You need to use a . to select the element with class recordId. Also use text() to get the value:
$thevalueIwanttoSave = $(this).siblings('.recordId').text();
alert($thevalueIwanttoSave);