Javascript PHP move row from one table to another - javascript

I have two tables on one page. The table at the top only has one row, because that particular table in the DB will only ever have one entry, the Tank of the Month. The bottom table shows the contents of another table in the database, 'uploads'. When an item is deleted from the bottom table, it deletes it from the DB and from the physical /uploads/ folder as expected. When an item is chosen from the bottom table as Tank of the Month, it is supposed to disappear from the bottom table, which it does correctly, then the top table is supposed to clear and the item that was chosen should automatically fade into the top table. I have tried many, many ways of doing this with no luck so far. The only way I can get the top table to refresh is by actually refreshing the page. This does what I want, but I want to do it without the page refresh.
totm.php (not the whole file as most of it works):
<!--put body stuff here-->
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card card-plain">
<div class="header">
<h4 class="title">Current Tank of the Month</h4>
<p class="category">This is your current tank of the month. </p>
</div>
<div class="content table-responsive table-full-width">
<?php
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
else
{
if (!$stmt = $mysqli->query("SELECT * FROM totm")) {
echo "Query Failed!: (" . $mysqli->errno . ") ". $mysqli->error;
}
echo "<table class='table table-hover'>";
echo "<thead>
<th>Image</th>
<th>Filename</th>
<th>Description</th>
</thead>
<tbody>";
while ($row = mysqli_fetch_array($stmt)) {
$i = $row["id"];
$f = $row["file"];
$d = $row["description"];
echo "<tr id='$i' file='$f' desc='$d'>";
echo "<td> <a href='../assets/img/totm/" . $row["file"] . "'><img class='thumbnail' src='../assets/img/totm/" . $row["file"] . "' alt='" . $row["file"] . "' /> </td>";
echo "<td>" . $row["file"] . "</td>";
echo "<td>" . $row["description"] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
if (mysqli_num_rows($stmt) == 0) {
echo "No records found.";
}
}
$stmt->free();
//$mysqli->close();
?>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card card-plain">
<div class="header">
<h4 class="title">Current Entries</h4>
<p class="category">Here you will find the current entries for the Tank of the Month contest. Select one as the new Tank of The Month and delete the rest. Keep it clean around here! </p>
</div>
<div class="content table-responsive table-full-width">
<?php
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
else
{
if (!$stmt = $mysqli->query("SELECT * FROM uploads")) {
echo "Query Failed!: (" . $mysqli->errno . ") ". $mysqli->error;
}
echo "<table class='table table-hover'>";
echo "<thead>
<th>Image</th>
<th>Name</th>
<th>Email</th>
<th>IP</th>
<th>Date</th>
<th>Description</th>
<th>Action</th>
</thead>
<tbody>";
while ($row = mysqli_fetch_array($stmt)) {
$i = $row["id"];
$f = $row["file"];
$d = $row["description"];
echo "<tr id='$i' file='$f' desc='$d'>";
echo "<td> <a href='../uploads/" . $row["file"] . "'><img class='thumbnail' src='../uploads/" . $row["file"] . "' alt='" . $row["file"] . "' /> </td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "<td>" . $row["ip"] . "</td>";
echo "<td>" . $row["date"] . "</td>";
echo "<td>" . $row["description"] . "</td>";
echo "<td>
<button class='btn btn-round btn-danger deleteitem'>Delete</button>
<div class='space-20'></div>
<button class='btn btn-round btn-success chooseitem'>Select</button>
</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
if (mysqli_num_rows($stmt) == 0) {
echo "No records found.";
}
}
$stmt->free();
$mysqli->close();
?>
</div>
</div>
</div>
</div>
</div>
</div>
totm-backend.js:
$(".deleteitem").click(function () {
var parent = $(this).closest('TR');
var id = parent.attr('id');
var file = parent.attr('file');
if (confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
data: { delete_id: id, delete_file : file },
URL: "totm.php",
success: function (msg) {
parent.fadeOut('slow', function () { $('#' + id).remove() });
}
});
}
return false;
});
$(".chooseitem").click(function () {
var parent = $(this).closest('tr');
var id = parent.attr('id');
var file = parent.attr('file');
var desc = parent.attr('desc');
if (confirm("Are you sure you want to promote this to Tank of the Month?")) {
$.ajax({
type: "POST",
data: { promote_id: id, promote_file: file, promote_desc: desc },
URL: "totm.php",
success: function (msg) {
parent.fadeOut('slow', function () { $('#' + id).remove() });
}
});
}
return false;
});

You could use the appendTo function to append the item into the proper table.
Check this post out on how to do it.
To get the "current" table, check out hasClass
I'm just learning javascript and jquery myself so there may be better ways.

Related

<div> content should display text "Data is empty" when there is no data to retrieve from database

Based on my question, I want to display the content of the div (id = "content") with a text (Data is empty) when there is no data to retrieve from the database. What I know is to use javascript. But I am still new in this programming skill. Can anyone help me?
Below is my code
<div class="row" id = "content">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card bg-light">
<div class="card-body double" style="height: 400px; overflow-y: scroll;">
<h4 class="card-title">All Booking</h4>
<table class="table table-bordered" >
<thead>
<tr>
<th>#</th>
<th>Requester</th>
<th>Factory</th>
<th>Room</th>
<th>Purpose</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody >
<?php
$query = $conn->query("SELECT * FROM booking LEFT JOIN room ON booking.Room_ID = room.Room_ID WHERE Admin_email = '$Email' AND EndTime > GETDATE() ORDER BY booking.Book_No DESC");
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$status=$row['Book_Status'];
if($status=="Approve")
{
$color="color:green";
}
else if($status=="Pending")
{
$color="color:blue";
}
else
{
$color="color:red";
}
echo "<tr>";
echo "<td>" . $row['Book_No'] . "</td>";
echo "<td>" . $row['Requested_by'] . "</td>";
echo "<td>" . $row['Fac_ID'] . "</td>";
echo "<td>" . $row['Room_Desc'] . "</td>";
echo "<td>" . $row['Meeting_Description'] . "</td>";
echo "<td style='$color'><strong>" . $status ."</strong></td>";
echo "<td>";
echo "<a class='btn btn-primary btn-block' href='../view_booking/view_booking.php?Book_No=". $row['Book_No'] ."' title='View Booking' data-toggle='tooltip'>View</a>";
echo "</td>";
echo "</tr>";
}
?>
</tbody>
</table><br>
</div>
</div>
</div>
</div>
You can wrap your <div> tag inside a condition based on your SQL query.
Example:
$query = $conn->query("SELECT * FROM booking LEFT JOIN room ON booking.Room_ID = room.Room_ID WHERE Admin_email = '$Email' AND EndTime > GETDATE() ORDER BY booking.Book_No DESC");
$count = mysqli_num_rows($query); // if your query doesn't returns any error.
if($count > 0) { ?>
<div id=content> your all contents here </div>
<?php } else { ?>
<div id="content"> Data is empty </div>
<?php } ?>

Column value not updated in the table

I am not able to update one column field. Please Suggest me what is the wrong thing in my code
index.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "logistics";
$lastId="";
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
$result = mysqli_query($con,"SELECT * FROM notification");
?>
<div class="table-inner-wrapper">
<h5 class="text- blll"> Active Alerts </h5>
<table class="table table-hover table-striped">
<tr class="t_head">
<th>ID </th>
<th>Forklift ID</th>
<th>Timestamp</th>
<th>Duration</th>
<th>Alert Details</th>
<th></th>
<th>Remark</th>
<th></th>
</tr>
<?php
while($row = mysqli_fetch_array($result)){
echo "<form action='' id='remarks' method='post'>";
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['forklift_id'] . "</td>";
echo "<td>" . $row['noti_start'] . "</td>";
echo "<td>" . $row['duration'] . " hr</td>";
echo "<td>" . $row['alert_details'] . "</td>";
echo "<td><i class='email' id='". $row['id'] ."'> <i class='fa fa-inbox fa-2x'> </i> </i> </td>";
echo "<td><textarea class='remarks' id='".$row['id']."'> ".$row['remarks']." </textarea></td>";
echo "<td><input type='button' class='btn btn-info remark' value='submit' id='".$row['id']."'></td>";
echo "</tr>";
echo "</form>";
}
?>
</table>
</div>
<script type="text/javascript">
$(() => {
$(document).ready(function(){
$(".remark").on('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
var remarks = $("textarea.remarks").val();
// alert(remarks);
// alert(id);
$.ajax({
url:'remark.php',
method:'POST',
data: {id: id, remarks: remarks},
success:function(data){
alert(data);
// return data;
}
});
});
});
})
</script>
remark.php
<?php
$conn = new mysqli('localhost', 'root', '', 'logistics');
$remarks = $_POST['remarks'];
echo $remarks;
$id = $_REQUEST['id'];
echo $id;
$sql = "UPDATE notification SET remarks='".$remarks."' WHERE id='".$id."' " ;
if($conn->query($sql)===TRUE){
echo "DATA updated";
}
?>
I am trying to update remarks column value on submit based on row id but it's updating only a first row of column value and if i click on the remaining rows it is not updating the remarks value.
A couple things:
I would change $id = $_REQUEST['id']; to $id = $_POST['id'];
Secondly, your <form> tag is inside your while loop which means you are echoing out a new form on every iteration. All of the forms will have the same id. This will cause you problems and fits the type of behavior that you are describing. Remove the <form> tags from the inside of the loop like so:
echo "<form action='' id='remarks' method='post'>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['forklift_id'] . "</td>";
echo "<td>" . $row['noti_start'] . "</td>";
echo "<td>" . $row['duration'] . " hr</td>";
echo "<td>" . $row['alert_details'] . "</td>";
echo "<td><i class='email' id='". $row['id'] ."'> <i class='fa fa-inbox fa-2x'> </i> </i> </td>";
echo "<td><textarea class='remarks' id='".$row['id']."'> ".$row['remarks']." </textarea></td>";
echo "<td><input type='button' class='btn btn-info remark' value='submit' id='".$row['id']."'></td>";
echo "</tr>";
}
echo "</form>";
This line:
var remarks = $("textarea.remarks").val();
will only give you the value of the first textarea with the class remarks. You need to access the remarks from the textarea associated with the button instead. You do have a problem though that you have multiple elements with the same id, so you need to fix that first. Try changing this code:
echo "<td><i class='email' id='". $row['id'] ."'> <i class='fa fa-inbox fa-2x'> </i> </i> </td>";
echo "<td><textarea class='remarks' id='".$row['id']."'> ".$row['remarks']." </textarea></td>";
to
echo "<td><i class='email' id='e". $row['id'] ."'> <i class='fa fa-inbox fa-2x'> </i> </i> </td>";
echo "<td><textarea class='remarks' id='t".$row['id']."'> ".$row['remarks']." </textarea></td>";
Now your textarea field has a unique id which is still related to $row['id']. So in your event code, you can write:
var remarks = $("#t" + id).val();
to get the value of remarks associated with that button.

Database row is not deleting, AJAX, PHP error

I want to remove DB row data from HTML table. I have an HTML table where I have called all the database table values. I want to give a delete order option to the user. I have used a delete button for that. To do this, I am trying to use ajax and jquery with php delete query. But the issue is When I click on delete it just deletes the HTML row data. It should delete that particular id row from DB as well. I need your help. Please let me know what I have done wrong? I am very much new to ajax and jquery.
remove.php
<?php
include "config.php";
$id = $_REQUEST['id'];
// Delete record
$query = "DELETE FROM mi_home_tv WHERE id='$id'";
mysqli_query($link,$query);
echo 1;
jquery+ajax code
<script src='jquery-3.0.0.js' type='text/javascript'></script>
<script type="text/javascript">
$(document).ready(function(){
// Delete
$('.delete').click(function(){
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
// AJAX Request
$.ajax({
url: 'remove.php',
type: 'POST',
data: { id:deleteid },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
});
});
</script>
Button Code:
echo "<td> <span id='del_<?php echo $id; ?>' type='submit' class=' delete btn c-theme-btn c-btn-uppercase btn-xs c-btn-square c-font-sm'>Delete</span> </td>";
php code:
<form method="post" action="remove.php">
<?php
echo " <thead>
<tr>
<th>Order ID</th>
<th>Date</th>
<th>Name</th>
<th>Store Name</th>
<th>Zip</th>
<th>City</th>
<th>Address</th>
<th>Contact</th>
<th>Tv Varient</th>
<th>Total</th>
<th>Delivery</th>
<th>Action</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
echo"<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rdate'] . "</td>";
echo "<td>" . $row['rname'] . "</td>";
echo "<td>" . $row['rstore'] . "</td>";
echo " <td>" . $row['rzip'] . "</td>";
echo "<td>" . $row['rcity'] . "</td>";
echo "<td>" . $row['raddress'] . "</td>";
echo "<td>" . $row['rphone'] . "</td>";
echo "<td>" . $row['rtv_varient'] . "</td>";
echo"<td>" . $row['ramount'] . "</td>";
echo"<td>" . $row['rdelivery'] . "</td>";
echo "<td> <input type='submit' value='delete' id='del_<?php echo $id; ?>' type='submit' class=' delete btn c-theme-btn c-btn-uppercase btn-xs c-btn-square c-font-sm'>Delete</button> </td>";
echo"</tr>";
}
?>
</form>
You should have a form which will have an input as follows:
<form method="post" action="remove.php">
<input type="submit" value="Delete" name="id" />
</form>

Master Detail with two tables

I would like to create a master - detail in php and javascript with two tables:
The First table is loaded from a database and it contains some categories.
When i click on a row in the first table I would like to view in a second table all subcategories of a selected category.
I have try with this but I'm not able to create the query for the subcategories table.
<div class="uk-grid">
<!-- First Table - List of Categories -->
<div class="uk-width-1-2" id="Gruppi" >
<div class="uk-panel uk-panel-box">
<h2>Gruppi</h2>
<?php
// Connessione al db
$con = mysqli_connect('localhost','root','','conti');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT Gruppo, Tipo FROM gruppi";
$result = mysqli_query($con,$sql);
echo "<section class=\"wrapper style5\">
<table id=\"table_gruppi\" class=\"uk-table uk-table-hover uk-table-striped uk-table-condensed\" > <thead> <tr>
<th>Gruppo</th>
<th>Entrata</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Gruppo'] . "</td>";
// Checkbox al posto di 1 o 0
if ($row["Tipo"]=='1') {
echo "<td> <input checked=\"\" type=\"checkbox\" disabled> </input> </td>";
} elseif ($row["Tipo"]=='0') {
echo "<td> <input type=\"checkbox\" disabled> </input> </td>";
}
echo "</tr>";
}
echo "</table></section>";
mysqli_close($con);
?>
</div>
</div>
<!-- Second Table - List of Subcategories -->
<div class="uk-width-1-2"><div class="uk-panel uk-panel-box"><h2>Sottogruppi</h2>
<p id="click-response"></p>
<?php
// Connessione al db
$con = mysqli_connect('localhost','root','','conti');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT Sottogruppo FROM sottogruppi WHERE Gruppo = ";
$result = mysqli_query($con,$sql);
echo "<section class=\"wrapper style5\">
<table id=\"table_gruppi\" class=\"uk-table uk-table-hover uk-table-striped uk-table-condensed\" > <thead> <tr>
<th>Sottogruppo</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Sottogruppo'] . "</td>";
echo "</tr>";
}
echo "</table></section>";
mysqli_close($con);
?>
</div></div>
<script type="text/javascript">
function onRowClick(tableId, callback) {
var table = document.getElementById(tableId),
rows = table.getElementsByTagName("tr"),
i;
for (i = 0; i < rows.length; i++) {
table.rows[i].onclick = function (row) {
return function () {
callback(row);
};
}(table.rows[i]);
}
};
onRowClick("table_gruppi", function (row){
var value = row.getElementsByTagName("td")[0].innerHTML;
document.getElementById('click-response').innerHTML = value + " clicked!";
console.log("value>>", value);
var sql_sottogruppi = "SELECT Sottogruppo FROM sottogruppi WHERE Gruppo = '" + value + "'"
});
</script>
I need some help or example.
thank you so much!

Bootstrap contextual table based off certain variable

I set up a table that grabs information from a Mysql database and displays it quit nicely. However i would like the table "row" to change colors based off the aging of the account? Any simple easy ways of achieving this?
Home.php
<div class="row">
<div class="col-md-12">
<table class="table table-bordered table-striped table-responsive">
<tr class="header">
<td>Rep</td>
<td>Date</td>
<td>Name</td>
<td>P_O</td>
<td>Due Date</td>
<td>Terms</td>
<td>Aging</td>
<td>Open Balance</td>
</tr>
<?php
while($row = mysql_fetch_array($query)) {
$className ="";
if ($row['Aging'] >= 45)
{
$className="clsRedRow";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44)
{
$className="clsYellowRow";
}
echo "<tr class='$className'>";
echo "<td>".$row[Rep]."</td>";
echo "<td>".$row[Date]."</td>";
echo "<td>".$row[Name]."</td>";
echo "<td>".$row[P_O]."</td>";
echo "<td>".$row[Due_Date]."</td>";
echo "<td>".$row[Terms]."</td>";
echo "<td>".$row[Aging]."</td>";
echo "<td>".$row[Open_Balance]."</td>";
}
?>
</table>
</div>
</div>
Try adding a class inline to the <tr> elements. Something like this:
<?php
while ($row = mysql_fetch_array($query))
{
$className = "";
if ($row['Aging'] < 50)
{
$className = "clsRedRow";
}
else
{
$className = "clsGreenRow";
}
echo "<tr class='$className'>";
echo "<td>" . $row[Rep] . "</td>";
echo "<td>" . $row[Date] . "</td>";
echo "<td>" . $row[Name] . "</td>";
echo "<td>" . $row[P_O] . "</td>";
echo "<td>" . $row[Due_Date] . "</td>";
echo "<td>" . $row[Terms] . "</td>";
echo "<td>" . $row[Aging] . "</td>";
echo "<td>" . $row[Open_Balance] . "</td>";
}
?>
Then, you'd need to have the proper styles set up in the HTML document (above the PHP script, not sure where the rest of your styles are set):
<style>
.clsRedRow{ background-color: red; }
.clsGreenRow{ background-color: green; }
</style>
I would probably add a class to the aging cells, and then iterate over them and check the value in a jQuery function to apply your styling based on the range the number falls in.
$("#some-table .aging").each(function() {
var age = $(this).html();
if (age <= 2) {
$(this).parent().css({"background-color" : "blue"});
} else if (age <= 5) {
$(this).parent().css({"background-color" : "yellow"});
} else if (age <= 8) {
$(this).parent().css({"background-color" : "red"});
}
});
Like this: http://codepen.io/jonathanrbowman/pen/epVBox

Categories

Resources