I found plenty of articles and solutions but for some reason my code still doesn't work. What am I missing?
Table: (creation works, important part is at the comment '! HERE')
<!-- Table with grades -->
<table class="table table-hover table-dark">
<caption>List of grades</caption>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Grade</th>
</tr>
</thead>
<tbody>
<?php
// fill table with data of database
if($subject != '') {
$query = "SELECT u.firstname, u.lastname, u.username, s.subject, g.grade FROM tbl_grades as g INNER JOIN tbl_users as u on g.studentID = u.ID INNER JOIN tbl_subjects as s on g.subjectID = s.ID where s.subject = ? and classID = ? order by u.lastname";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $subject, $class);
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows > 0) {
$count = 0;
while($row = $result->fetch_assoc()){
if(($count % 2) != 0) {
echo '<tr class="bg-success">';
} else {
echo '<tr>';
}
echo '<th scope="row">' . ($count + 1) . '</th>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
//! HERE
echo '<td class="grade_td" contentEditable="false">' . $row['grade'] . '</td>';
echo '</tr>';
$count++;
}
}
$result->free();
}
?>
</tbody>
</table>
<button class="btn_edit">Edit List</button>
Toggle with javascript, jquery (multiple versions, none of them work):
$(document).ready(function() {
// v1
$('.btn_edit').click(function() {
if($('.grade_td').contentEditable == false) {
$('.grade_td').contentEditable = true;
}
});
// v2
$('.btn_edit').click(function() {
$('td[contenteditable="false"]').contentEditable = true;
});
// v3
$('.btn_edit').click(function() {
$('.grade_td[contenteditable="false"]').contentEditable = true;
});
// more variations, same concepts
});
btw. the button event works fine
You need to use the jQuery attr function or set the attribute value on the element itself not the jQuery object.
$('.btn_edit').click(function() {
$('.grade_td').attr('contenteditable', 'true') ;
});
I'm not sure about custom attributes, but I would have made this a data attribute:
echo '<td class="grade_td" data-contenteditable="false">' . $row['grade']
and then referenced like this:
$('td.grade_td[data-contenteditable="false"]');
Related
I have my index.php where I'm going to make an Ajax request to the server and display the response (as a table).
<div id="result"></div>
<script>
$('#loading-image').show();
function load_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#result').html(data);
}
});
}
load_data();
</script>
result will have the value of $output:
<?php
include '../../variables.php';
include '../../_Database.php';
$db = Database::getInstance();
$minDuration;
$maxDuration;
$tableRowCounter;
$output = '<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Artikel</th>
<th scope="col">Durchlaufzeit</th>
<th scope="col">Neue Durchlaufzeit</th>
<th scope="col">Bestätigen</th>
</tr>
</thead>
<tbody>
';
$result = mysqli_query($db->link, "SELECT * FROM `Person_changes_Article`");
while ($row = mysqli_fetch_assoc($result))
{
$result2 = mysqli_query($db->link, "SELECT * FROM `Article`");
while ($row2 = mysqli_fetch_assoc($result2))
{
if ($row['Article_idArticle'] == $row2['idArticle'])
{
$minDuration = ($row2['duration'] / 10) * 9;
$maxDuration = ($row2['duration'] / 10) * 11;
if ($row['newDuration'] < $minDuration OR $row['newDuration'] > $maxDuration)
{
$tableRowCounter++;
$output .= '
<tr>
<th scope="row">'.$tableRowCounter.'</th>
<td>'. $db->getArticleString($row2["idArticle"]) ." - " . $row2["idArticle"]. '</td>
<td>'. $row2["duration"] .'</td>
<td>'. $row["newDuration"] .'</td>
<td><input type="checkbox" id="t'. $tableRowCounter .'" name="name" value="value"></td>
</tr>
';
}
}
}
}
$output .= '
</tbody>
</table>';
echo $output;
?>
I intend to add checkboxes to each row in the table. Where a user simply can make a choice which rows should be changed and sent back to the server.
I don't know how to get the values out of the td's.
I tried to assign an automatically generated id to each checkbox with $tableRowCounter.
However, when I try to access the id of let's say #t1 with jquery it doesn't work.
like so:
$(document).ready(function(){
$('#t1').prop('checked', true);
});
After all, it just feels bad preparing auto-generated id values in the backend.
What I want to do is (or the user) to check checkboxes of any row, and hit a button which sends the values in the table of that specific row to the server.
It doesn't even matter how the server is receiving the data. I'd be totally fine with an array of all the values from all rows of the table (just the checked ones though)
How? Please help.
First, for the third code snippet, the $('#t1') was unavailable because the table was not rendered when document was ready. The table was inserted after the AJAX request response. If you want to initialize something, do it in the AJAX request success callback.
For submitting the checked rows, attribute selector is recommended.
the html output:
$output .= '
<tr>
<th scope="row">'.$tableRowCounter.'</th>
<td>'. $db->getArticleString($row2["idArticle"]) ." - " . $row2["idArticle"]. '</td>
<td>'. $row2["duration"] .'</td>
<td>'. $row["newDuration"] .'</td>
<td><input type="checkbox" data-id="'. $row['id'] .'" name="name" value="value"></td>
</tr>';
then the button handler:
$("#submit").onclick(function() {
var selectedIds = []
$("table input[type=checkbox]").forEach(function(i, elem) {
var cb = $(elem)
if (cb.prop('checked')) {
selectedIds.push(cb.attr('data-id'))
}
// send selectedIds to server
})
})
#cuiyajie
Thank you. I couldn't completely apply your solution to my problem.
However, I saw how it's made and wrote it again on my level of understanding JavaScript.
I know this shouldn't be made, but I didn't see any reason why I would run into issues having not unique IDs
I have given my tds IDs. like so:
<tr>
<th scope="row">'.$tableRowCounter.'</th>
<td>'. $db->getArticleString($row2["idArticle"]) .'</td>
<td id="article">'. $row2["idArticle"] .'</td>
<td id="duration">'. $row2["duration"] .'</td>
<td id="newDuration">'. $row["newDuration"] .'</td>
<td>'. $db->getName($row["Person_idPerson"]) . " ".$db->getLastName($row["Person_idPerson"]) .'</td>
<td id="check"><input type="checkbox" id="check" name="name" value="value"></td>
</tr>
I can then easily loop through the tds and push the values into arrays:
var article = [];
var duration = [];
var newDuration = [];
var check = [];
$("td[id='article']").each(function(){
article.push($(this).text());
})
$("td[id='duration']").each(function(){
duration.push($(this).text());
})
$("td[id='newDuration']").each(function(){
newDuration.push($(this).text());
})
$("input[id='check']").each(function(){
if ($(this).is(':checked')){
check.push(1);
}else{
check.push(0);
}
})
And post the arrays using Ajax
$.ajax({
type:'POST',
url:'storeData.php',
data: { article: article,
duration: duration,
newDuration: newDuration,
check: check
},
success:function(data){
//alert(data)
},
});
in storeData.php I can then work with those arrays and do whatever I want
$article = $_POST['article'];
$duration = $_POST['duration'];
$newDuration = $_POST['newDuration'];
$check = $_POST['check'];
print_r($article);
print_r($duration);
print_r($newDuration);
print_r($check);
I have following loop in php:
foreach ($sid as $key => $value) {
$sql = " a sql query ";
$vehicle->rowQuery($sql);
$numRows = $vehicle->rows;
while ( $data = $vehicle->result->fetch_assoc()) {
$vid = $data['vid'];
$vehicleName = $data['vehicleName'];
$noOfSeat = $data['noOfSeat'];
$seatBooked = $data['seatBooked'];
$supplierName = $data['supplierName'];
echo "<table class='table table-bordered table-condensed table-striped'>";
echo "<tr>";
echo "<th colspan='4' class='success'>
<label class='checkbox-inline'>
<input type='checkbox' class='vehicleClass' name='vid[]' value='{$vid}'>$vehicleName<strong> ( $noOfSeat Seats available) - $supplierName
</label>
<div class='pull-right'><a href='#' class='hideMe'>Show/Hide</a></div></strong>
<input type='hidden' name='noOfSeat[$vid]' value='$noOfSeat'>
</th>";
echo "</tr>";
echo "<tr>";
echo "<th colspan='4'>All Seats</th>";
echo "</tr>";
$count = 0;
for ($seat=1; $seat <= $noOfSeat; $seat++) {
if($count % 4 == 0) {
echo "</tr><tr class='toggleMe'>";
}
echo "<td><label class='checkbox-inline'><input type='checkbox' name='seatNo[$vid][]' value='$seat'>Seat $seat </label></td>";
$count++;
}
echo "</table>";
}
if( $numRows == 0 ) {
echo "<table class='table table-bordered table-condensed table-striped'>";
echo '<tr><td class="alert alert-warning">Your selected vehicle is not available.</td></tr>';
echo "</table>";
}
}
It's output is like that:
Now, I am trying to show and hide the corresponding All Seats Checkbox list whne I click on show/hide link using following jQuery:
$(document).ready(function(){
$('.hideMe').click(function() {
$(this).next('.toggleMe').toggle();
});
});
But show/hide it's not working. Can you guys tell me how can I solve it?
Thanks.
===================
Update:
When the loop result is this :
then using this code it's working fine:
$(document).ready(function(){
$('.hideMe').click(function() {
$('.toggleMe').toggle();
});
});
Do you use ajax to get the html?
if yes, you had better use $('body').on('click,'.hideMe',function() {})
and tr is not next element of .hideMe
You can try this code.
$(document).ready(function(){
$('body').on('click','.hideMe',function() {
$(this).parents('table').find('.toggleMe').toggle();
});
});
I think you should use on('Click',function(){ }) instead of click try this
$(document).ready(function(){
$('body').on('click', '.hideMe', function() {
$(this).next('.toggleMe').toggle();
});
});
I think your structuring with "<tr>" is not correct in
if($count % 4 == 0) {
echo "</tr><tr class='toggleMe'>";
}
this will add a </tr> at the beginning of each toggleMe class.
I have the following table to be saved to the DB. the $varline is a counter, used to total up the row values.
<table id="table1" border="1">
<tbody>
<tr>
<th>First Name</th>
<th>id</th>
<th>Price</th>
<th>Qty</th>
<th>Select</th>
</tr>
<tr>
<td>A1</td>
<td><input type="text" value="$id" name='item[$varline][id]'></td>
<td><input type="text" value="$price" name='item[$varline][price]'></td>
<td><input type="text" name='item[$varline][quantity]'></td>
<td><input type="checkbox" name="item[$varline][check-tab1]"></td>
</tr>
</tbody>
</table>
I need to save the data to the DB using POST method...I am using the following javascript to calculate the totals:
function calcTot(i){
unitPrice = document.getElementById("myTable").rows[i].cells[1].childNodes[0].value;
quantity = document.getElementById("myTable").rows[i].cells[2].childNodes[0].value;
amount= parseFloat(price) * parseFloat(quantity);
document.getElementById("myTable").rows[i].cells[3].childNodes[0].value = amount.toFixed(2);
}
The PHP code that I have constructed so far is given below:
if (isset($_POST['submit'])) {
$reservation_id = $_POST['res_id'];
$item_id = $_POST['item']['product_id'];
$item_quantity = $_POST['item']['quantity'];
$item_discount = $_POST['item']['discount'];
$item_unit_price = $_POST['item']['price'];
$item_amount = $_POST['item']['amount'];
$items_total = $_POST['item']['total'];
$items_checked = $_POST['checked_pro'];
$invoiceId = $_POST['invoice_id'];
foreach ($item_id as $key => $value) {
$check_item_id = "SELECT item_id from products where item_id='" . $conn->real_escape_string($item_id[$key]) . "'LIMIT 1"; //check if item exist
$resultset = $conn->query($check_item_id);
if ($resultset->num_rows == 0) {
$insert_product = "INSERT INTO `invoice_items` (`id`, `invoice_id`, `product_id`, `quantity`, `price`, `amount`) VALUES (NULL, '" . $conn->real_escape_string($invoiceId) . "', '" . $conn->real_escape_string($item_id) . "', '" . $conn->real_escape_string($item_quantity) . "', '" . $conn->real_escape_string($item_unit_price) . "', '" . $conn->real_escape_string($item_amount) . "')";
$insert_item = mysqli_query($conn, $insert_product);
if (!$insert_item) {
echo "<script>";
echo "alert('Error inserting!')";
echo "</script>";
}
}
I have a table in an oracle database that I am showing on a web page. I used bootstrap to style my page and dataTables for pagination and search as well as sorting. I want to update any particular row at anytime using the unique ID column(BID), so I have added an update link next to each row using the foreach loop.
My problem now is to get the logic to build that functionality to make the update link. I want to:
Find a way to know which row the user has clicked to update, and retrieve that record/row to a form for update using the ID.
Challenge:
I am using a loop to fill the table and I can't think of a way to link each row ID to the update link by it. I tried filling an array with the ID's but how to connect what update link to what ID for retrieval beats me.
I am using html and PHP as well as some simple javascript. I am not good at javascript and have little knowledge in ajax also. I am yet to learn them but I understand they are the best to use for such things. Perhaps, I am not using the best approach, so if anybody can help me out with a much better one within my scope. Find my code below.
<table class="table table-striped" id="scriptstable">
<thead>
<tr>
<th>Update</th><!--This is where update links are-->
<th>Place</th>
<th>Report Name</th>
<th>Index</th>
<th>Source</th>
<th>Core Field</th>
<th>Description</th>
<th>ID</th>
</tr>
</thead>
<?php
//Connection string is here
$stid = oci_parse($conn, 'SELECT * FROM mytable ORDER BY REPORT_NAME');
oci_execute($stid);
echo "<tbody>";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
echo "<tr>";
echo " <td><a data-toggle='modal' data-target='#myModal' href='#' >Update</a>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
} $bid[]=$row['BID'];//Array that stores ID as they come
echo "</tr>";
}
?>
</tbody>
</table>
UPDATE:
$ajaxAction = $_REQUEST['ajaxaction'];
if (!method_exists('ajaxHandler', $ajaxAction)) {
die("No such action {$ajaxAction}");
}
$handler = new ajaxHandler();
$handler->$ajaxAction();
class ajaxHandler
{
function __construct()
{
//just an empty constructor
}
function updateRow()
{
//Connection
$conn = oci_connect('username', 'password', 'localhost/XE', 'WE8MSWIN1252');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$BID = $_REQUEST['BID'];
$stid = oci_parse($conn, 'SELECT * FROM Bo_repository WHERE BID = {$BID}');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
// echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
echo " <td><a id='{$row['BID']}' href='#' onclick='updateRow(this)'>Update</a></td>";
//header("Location:index.php");
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
}
}
?>
When you emit your rows in the table you can assign the id to the table row... I usually do it concat with row or something... and include the id as the id of your tag. You can then use the onclick to call a javascript function using ajax to update your table row dynamically e.g.
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
echo "<tr id='row_{$row['BID']}'>";
echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
$bid[]=$row['BID'];//not sure this is really needed anymore
echo "</tr>";
}
The updateRow function would be something like this... In a script tag of course...
function updateRow(element) {
var id = jQuery(element).prop('id');
var url = 'your_back_end.php_file_that_handles_Ajax';//e.g. AjaxHandler.php
var postArg = {};
postArg['BID'] = id;
postArg['ajaxaction'] = 'updateRow';
jQuery.ajax({
url: url,
type: "post",
data: postArg,
success: function (response) {
jQuery('#row_' + id).html(response);
},
error: function(response){
console.log(response);
}
});
}
Your backend file would be pretty simple... I create a class called AjaxHandler and pass all ajax calls to the class for whatever processing I need to do...
Your file could be something like this example...
AjaxHandler.php
<?
$ajaxAction = $_REQUEST['ajaxaction'];
if (!method_exists('ajaxHandler', $ajaxAction)) {
die("No such action {$ajaxAction}");
}
$handler = new ajaxHandler();
$handler->$ajaxAction();
class ajaxHandler
{
function __construct()
{
//just an empty constructor
}
function updateRow()
{
$BID = $_REQUEST['BID'];
$stid = oci_parse($conn, 'SELECT * FROM mytable WHERE BID = {$BID}');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
}
}
This is a very basic async dynamic update using php and ajax...
Hope this helps...
I have a HTML table the displays record from database.
Below is a screenshot of my table
There is a button in a TD (i.e column 5,7,9), when I click the button I want to perform function to display a popup box with html table.
Before that I want to pass the value of mcc and mnc and also want to pass the column name (i.e if i clicked the button near 5xx i want pass 5xx if 6xx I want to pass 6xx) to the page where there is a query to display the table. And have separate php code to retrieve th and td from database.
I tried but I don't know how to pass this value to javascript then to php page that contains query to display the table. Thanks
This is my HTML markup:
<table>
<th style="text-align:center;width:92px">MCC</th>
<th style="text-align:center;width:92px">MNC</th>
<th style="text-align:center;width:92px">MNP</th>
<?
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i = 0;
while($rows = mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows[0];
echo "<th>" . $columnArray[$i] . " <span> <img id='logo' src='/image/Picture2.png' style='margin:-62px -21px -9px 32px'></span></th>";
echo "<th style= 'width:20px;'></th>";
$i++;
}
?>
<?php
$sql = mysql_query("SELECT * FROM supplierprice ");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo ' <td class="edit region '.$rows["supp_price_id"].'">'.$rows["region"].'</td>
<td class="edit country '.$rows["supp_price_id"].'">'.$rows["country"].'</td>
<td class="edit networkname '.$rows["supp_price_id"].'">'.$rows["networkname"].'</td>
<td id="mcc" class="edit mcc '.$rows["supp_price_id"].'">'.$rows["mcc"].'</td>
<td id="mnc" class="edit mnc '.$rows["supp_price_id"].'">'.$rows["mnc"].'</td>
<td class="edit mnp '.$rows["supp_price_id"].'">'.$rows["mnp"].'</td>';
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i=0;
while($rows1=mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows1[0];
echo '<td width="0px;" class="edit '.$columnArray[$i].' '.$rows["supp_price_id"].'">'.$rows[$columnArray[$i]].'</td>';
echo '<td><input type="button" onclick="myFunction()" value="" /></td>';
$i++;
}
echo '</tr>';
} ?>
</table>
Javascript
<script>
function myFunction() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "testpage2/config.php";
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
var vars = "mcc="+mcc+"&mnc="+mnc;
hr.open("POST", url, true);
hr.send(vars);
}
</script>
but it not passing the value of mcc and mnc also the column
First of all assign Id to table:
<table>
like:
<table id="contentTable">
Now use below code of jQuery:
$(document).ready(function ()
{
$('#tableId').find('th').each(function ()
{
$(this).click(function ()
{
var thValue = $(this).html();
alert(thValue) // here is value of th on you have click
});
});
});
Cheers!!!
You could try to use something like "generic javascript":
<?php //some stuff
$mcc = "some value";
?>
<script type="text/javascript">
var myVariable = <?php echo $mss; ?>
</script>