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.
Related
I'm currently working on displaying a table containing a list of alarms, where each row contains a checkbox that determines whether the user has already viewed that alarm or not. Here's
an image:
So far, I managed to check/uncheck the checkbox given its state in the database. What I want to do, and don't exactly know how to, allow the user to check/uncheck a checkbox and immediately update the database with this new state without pressing a submit button. The code that I have right now is the following.
<div class="card-body table-responsive p-0">
<form action=modules/alarms.php method="POST">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Tipus</th>
<th>Data</th>
<th>Vista</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result->fetchAll() as $row){
if ($row[4] == 1){
$status = "checked";
}else{
$status = "";
}
echo
'<tr data-widget="expandable-table" aria-expanded="false">
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
<td><input type="checkbox" name="chk1[]" value="viewed" '.$status.'></td>
</tr>
<tr class="expandable-body">
<td colspan="5">
<p>
<video width="416" height="416" controls>
<!-- el 42 es la cabecera C:/... fins videos-->
<source src="'.substr($row[3], 42).'" type="video/mp4">
Your browser does not support the video tag.
</video>
</p>
</td>
</tr>';
}
?>
</tbody>
</table>
And the PHP code I have (I don't have the code that will update values on the database, but I'll figure that out. I want to know how I could retrieve the value of the checkbox of every row and its ID so I can update it on the database.
$ei = $_POST['chk1'];
if ($_POST["chk1"] == "chk1") {
for ($i = 0; $i < sizeof($checkbox1); $i++) {
print_r($checkboxl[$i]);
}
}
To solve this problem, first I had to add some fields to the checkbox input. WIth those changes, the table is generated as it follows:
<tr data-widget="expandable-table" aria-expanded="false">
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
<td><input type="checkbox" name="id" id="viewed" value="'.$row[0].'" '.$status.'></td>
</tr>
After this is done, simply add a script that will retrieve the values from the clicked checkbox and pass them to the necessary PHP function:
$("input").change(function() {
if ($(this).is(':checked')){
var viewed=1;
}else{
var viewed = 0;
}
var id = $(this).val();
$.ajax({
url:"modules/alarms.php",
method:"POST",
data:{viewed:viewed,id:id,},
success: function(data){
},
});
Please note that the 'url' field is the relative path where our PHP function is implemented.
And now, simply update the database with the checkbox value (I'm using PDO objects) as it follows:
<?php
if(isset($_POST["viewed"])) {
$id = $_POST["id"];
$viewed = $_POST["viewed"];
$sql="UPDATE `alarms` SET `viewed` = '$viewed' WHERE (`id` = '$id')";
if($connection->query($sql) === TRUE){
echo "Success";
} else {
echo "error" . $sql . "<br>".$connection->error;
}}?>
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 trying to build an edit page for editing my Previous Posts
so when i click edit link in front of a post it sends post id to edit.php
now here is my problem i want to check a radio box in edit page that shows my current post's category
I have a function like this:
function category($name,$postid){
if( $name == $postid)
{
return "checked";
}
}
in edit.php
$postid=$_GET['postid']
$query=mysqli_query($con,"SELECT *FROM category");
while($s=mysqli_fetch_array($query)){
echo
'<table width="200" border="1">
<tbody>
<tr>
<td>'.$s['category_name'].'</td>
<td><input type="radio" name="post_category" value="'.$s['category_name'].'" '.category($s['id'],$postid).'></td>
</tr>
</tbody>
</table>';
}
but it doesn't check the radio box
Its hard to tell without actually seeing what is not matching, but from your naming, it looks like you are matching the Id to the Name. If you are matching Id's, then you should use parseInt to make sure you are dealing with integers and comparing data in the same format.
You should tell to the PHP to write the return from the function:
Edit #1
changing the function to always return something
function category($id, $postid) {
if( $id== $postid)
{
return "checked";
}
return null;
}
The return will fill the var $checked or with "checked" or with null
while($s = mysqli_fetch_array($query)) {
$checked = category($s['id'], $postid);
echo
'<table width="200" border="1">
<tbody>
<tr>
<td>'.$s['category_name'].'</td>
<td>
<input... ' . $checked . '>
</td>
</tr>
</tbody>
</table>';
}
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);