Question:
I have a div element with id of "tableholder" which is purely to hold the output on a javascript function that pulls data via ajax from a PHP file.
Within the tableholder element, is a list.js table that works if we simply include he php file instead of calling it via ajax and setting it via innerHTML = "".
How do I use the contents of innerHTML of the tableholder div when it has been created dynamically?
Code so far:
PHP File called:
<?php
// Connection details for the database being called.
include 'connection.php';
// Putting the query to the database in a variable called "$assets".
$assets = "SELECT * FROM assetregister.getassets";
$assetPull = $conn->query($assets);
$output = "";
// Pulling all of the details from the database and displaying them on the page within the inidividual divs.
if ($assetPull->num_rows > 0) {
$output .= "<div id='users'>";
$output .= "<input class='search form-control mt-2' placeholder='Search...' />";
$output .= "<div class='m-2'>";
$output .= "<button class='sort btn' data-sort='model'>Sort By Model</button>";
$output .= "<button class='sort btn ml-2' data-sort='domain'>Sort By Domain</button>";
$output .= "<button class='sort btn ml-2' data-sort='location'>Sort By Location</button>";
$output .= "</div>";
$output .= "<table class='table table.hover list'>";
$output .= "<thead>";
$output .= "<th style='text-align: center;'>Model</th>";
$output .= "<th style='text-align: center;'>Serial Number</th>";
$output .= "<th style='text-align: center;'>Asset Number</th>";
$output .= "<th style='text-align: center;'>Domain</th>";
$output .= "<th style='text-align: center;'>Location</th>";
$output .= "<th style='text-align: center;'>Type</th>";
$output .= "</thead>";
while ($row = $assetPull->fetch_assoc()) {
$output .= "<tbody class='list' style='text-align: center;'>";
$output .= "<td class='model'>" . $row['modelName'] . "</td>";
$output .= "<td class='serialNumber'>" . $row['serialNumber'] . "</td>";
$output .= "<td class='assetNumber'>" . $row['assetNumber'] . "</td>";
$output .= "<td class='domain'>" . $row['domain'] . "</td>";
$output .= "<td class='location'>" . $row['locationName'] . "</td>";
$output .= "<td class='type'>" . $row['type'] . "</td>";
}
$output .= "</tbody>";
$output .= "</table>";
$output .= "</div>";
// If there is no rows in the table that is being called then they will display 0 Results... See below.
} else {
$output .= "0 results";
}
echo $output;
$conn->close();
?>
This works:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<?php include 'scripts/getAsset.php'; ?>
</main>
</div>
</div>
</div>
<script>
populatetable('tableholder');
window.onload = function () {
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
</script>
This outputs the table and all of the list.js functions work fine as expected.
This Doesn't Work:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<!-- Pulling in the results of the assets (most recent assets) -->
<div id="tableholder"></div>
<!-- end -->
</main>
</div>
</div>
</div>
<!-- PHP include for the footer -->
<?php include 'assets/layout/footer.php'; ?>
<!-- end -->
<script>
populatetable('tableholder');
window.onload = function (){
var options = {
valueNames: [ 'model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
function populatetable(name){
$.ajax({
url: "scripts/getAssets.php",
success: function(data){
document.getElementById(name).innerHTML = data;
}
})
}
</script>
What I can assume:
From the various console.log lines and php echos I have put in to test the code, it would appear that the issue it that the javascript command for initiating the list.js table isn't able to find the "user" table that is created by the document.getElementById(name).innerHTML = data; in the populatetable() function. I know this because the folllowing shows blank:
console.log(document.getElementById(tableholder).innerHTML);
What am I doing wrong, or is it not possible to pull the innerHTML data of a dynamically created element?
The problem is that by the time you're calling List(), the ajax call hasn't finished yet, since it's asynchronous.
Try this instead:
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList;
$(document).ready(function() {
populatetable('#tableholder');
});
function populatetable(id) {
$.ajax({
url: "scripts/getAssets.php",
success: function(data) {
$(id).html(data);
userList = new List('users', options);
}
});
}
Here I'm using jQuery everywhere it's useful, and I'm calling List() only after the data is actually inserted.
Also note, that like I mentioned in my comment, you need to move the <tbody> line outside the loop.
Related
Can anyone suggest some alternative solution for this problem.
I've made a popup form which i use css and javascript to trigger the display to none or flex every time i click into a specific button which is great. But this method seems to not work on a table as you can see below i've done a simple query which i just fetch some of the essentials and included some buttons to use to trigger the popup form.
PHP/HTML CODE
<tbody>
<?php
$res=mysqli_query($link,"SELECT CONCAT(c.firstname, ' ', c.lastname) AS fullname, c.* FROM user_registration c");
while($row=mysqli_fetch_array($res))
{
echo "<tr>";
echo "<td>"; echo $row["id"]; echo "</td>";
echo "<td>"; ?> <img src="<?php echo $row["image"]; ?>" height="100" width="100"> <?php echo "</td>";
echo "<td>"; echo $row["fullname"]; echo "</td>";
echo "<td>"; echo $row["username"]; echo "</td>";
echo "<td>"; echo $row["id"]; echo "</td>";
echo "<td>"; echo $row["id"]; echo "</td>";
echo "<td>"; echo $row["id"]; echo "</td>";
echo "<td>"; echo $row["id"]; echo "</td>";
echo "<td>"; ?> <button class="btn btn-success" style="width: 100%">Accept</button><?php echo "</td>";
echo "<td>"; ?> <button class="btn btn-danger" style="width: 100%">Decline</button><?php echo "</td>";
echo "<td>"; ?> <button class="btn btn-success" style="width: 100%">View Message</button><?php echo "</td>";
echo "</tr>";
}
?>
</tbody>
JAVASCRIPT CODE
document.getElementById("declineB").addEventListener("click", function(){
document.querySelector(".popup3").style.display = "flex";
})
document.getElementById("closeDecB").addEventListener("click", function(){
document.querySelector(".popup3").style.display = "none";
})
When you have multiple elements with id declineB, document.getElementById("declineB") can actually only get the first element with id declineB. The effect you want will only appear when an element whose id is declineB. When click others, no click event will be triggered.
When you use css class, you can add click event to every html element of same class:
let elements = Array.from(document.getElementsByClassName('spacer'))
for (let element of elements) {
element.addEventListener('click', ...)
}
I have 2 text files and read their content into 2 arrays using php. Then I create a table and display it on my site. I now want to color every cell from array 2 (column 2) based on certain values.
For Example:
if a value from array2 contains "busy", it shall be formatted red, if
it contains "available", it shall be formatted green.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post" class="formbody">
<div class="codetable">
<?php
$file1 = "c:/presencetool/ramfile1.txt";
$file2 = "c:/presencetool/ramfile2.txt";
$line1= file($file1, FILE_IGNORE_NEW_LINES);
$line2 = file($file2, FILE_IGNORE_NEW_LINES);
$combine = array_combine($line1, $line2);
$html = "<table align=center>";
$html .= "<tr><td width=300px></td><td></td></tr>";
$i = 1;
foreach ($combine as $file1 => $file2):
$html .= "<tr>";
$html .= "<td>".$file1."</td>";
$html .= "<td>".$file2."</td>";
$html .= "</tr>";
$i++;
endforeach;
$html .= "</table>";
echo $html;
?>
<div class="codelabel">
</div>
</div>
</form>
</body>
</html>
I tried some possible solutions but could not bring it to work.
Any ideas? If there is any Information I should provide, just ask.
edit:
content of ramfile 1&2:
ramfile1:
User#1
User#2
User#3
...
User#n
ramfile2:
Busy
Busy
Available
Busy
...
<?php
$path = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'demo'.DIRECTORY_SEPARATOR;
$file1 = $path.'ramfile1.txt';
$file2 = $path.'ramfile2.txt';
if(file_exists($file1) && file_exists($file2)) {
$line1= file($file1, FILE_IGNORE_NEW_LINES);
$line2 = file($file2, FILE_IGNORE_NEW_LINES);
$combine = array_combine($line1, $line2);
$html = '<table align="center">';
$html .= '<tr><td width="300px"></td><td></td></tr>';
$i = 1;
foreach ($combine as $key => $value):
$html .= '<tr class="'.$value.'">';
$html .= '<td>'.$key.'</td>';
$html .= '<td>'.$value.'</td>';
$html .= '</tr>';
$i++;
endforeach;
$html .= '</table>';
echo $html;
}
?>
<style>
.Busy { background-color: #f2a179;}
.Available { background-color: #00ff00;}
</style>
foreach ($combine as $file1 => $file2):
This line makes no sense at all. It will probably run but it won't do what you describe. I think you really want something like....
foreach ($file1 as $i=>$value) {
$html .= "<tr>";
$html .= "<td>".$file1[$i]."</td>";
$html .= "<td>".$file2[$i]."</td>";
$html .= "</tr>";
}
But that you are resolving data in one file from another based on the line number is a very bad choice of data structure.
if a value from array2 contains "busy", it shall be formatted red, if it contains "available", it shall be formatted green.
There are lots of ways to do this. You could call a function....
$bgcolor=lookup_css_class($file2[$i]);
$html .= "<td class='$bgcolor'>$file2[$i]</td>";
Or you could use dependancy injection, or you could use an array lookup. Alternatively you could simply declare CSS classes based on the value and inject the value as the class name for the TD (but bear in mind this allows someone with control over the data to inject html/javascript into your page:
td.busy {background-color: red;}
td.free {background-color: green;}
...
$html .= "<td class='$file2[$i]'>$file2[$i]</td>";
I will insert new boostrap card inside my page. My problem, I have not success to include a new card inside my content.
When i click on insert, the card is not displayed
Below the code
display a new boostrap card if record exist
<div class="row">
<button type="button" class="btn btn-primary" aria-label="Insert" id="insert">
<span aria-hidden="true">Insert</span>
</button>
</div>
<div class="row">
<ul class="row list-unstyled" id="list">
<?php
$i = 0;
while ($QoptionValue->fetch()) {
.....
?>
<li class="col-md-4" id="element'<?php echo $i; ?>">
<div class="card">
<h4 class="card-header">Card title <a class="close" href="#">×</a></h4>
<div class="card-body">
<div class="card-text">
<div><?php ..... ?></div>
</div>
</div>
</li>
<?php
$i++;
}
?>
</ul>
</div>
Display a new card or first card inside the content
<?php
$card = '<li class="col-md-4" id="element0">';
$card .= '<div class="card">';
$card .= '<h4 class="card-header">Card title <a class="close" href="#">Remove</a></h4>';
$card .= '<div class="card-body">';
$card .= '<div class="card-text">';
$card .= '<div>';
for ($l=0, $n=count($languages); $l<$n; $l++) {
$card .= Language->getImage($languages[$l]['code']) . ' ' . HTML::inputField('option_value[' . $i . '][option_value_description][name][' . $l . ']', $options_name) . '<br />';
$card .= HTML::hiddenField('option_value[' . $i . '][option_value_description][language_id][' . $l . ']', $options_name);
}
$card .= '</div>';
$card .= '<div>';
$card .= HTML::inputField('option_value[' . $i . '][sort_order]', $QoptionValue->value('sort_order'), 'id="sort_order[' . $i . ']"');
$card .= '</div>';
$card .= '<div>';
$card .= '</div>';
$card .= '</div>';
$card .= '</li>';
?>
<script>
$('#insert').click(function(){
$( "ul#list" ).append( "<?php echo $card; ?>" );
});
</script>
<script type="text/javascript">
$('.close').click(function(){
var $target = $(this).parents('li');
$target.hide('slow', function(){ $target.remove(); });
})
</script>
console error
it seems on this line has a problem :
$( "ul#list" ).append(""<li class=\"col-md-4\" id=\"element0\"><div class=\"row\"><div class=\"col-md-12\"><div class=\"card\"><h4 class=\"card-header\"><a class=\"close\" href=\"#\">Supprimer<\/a><\/h4><div class=\"card-body\">Nom de la valeur<div><img src=\"http:\/\/localhost\/test_option\/shop\/sources\/third_party\/flag-icon-css\/flags\/4x3\/gb.svg\" alt=\"Anglais\" title=\"Anglais\" width=\"16\" height=\"12\" \/> <input type=\"text\" name=\"option_value[0][option_value_description][name][0]\" class=\"form-control\" \/><br \/><input type=\"hidden\" name=\"option_value[0][option_value_description][language_id][0]\" \/><img src=\"http:\/\/localhost\/test_option\/shop\/sources\/third_party\/flag-icon-css\/flags\/4x3\/fr.svg\" alt=\"Francais\" title=\"Francais\" width=\"16\" height=\"12\" \/> <input type=\"text\" name=\"option_value[0][option_value_description][name][1]\" class=\"form-control\" \/><br \/><input type=\"hidden\" name=\"option_value[0][option_value_description][language_id][1]\" \/><\/div><div class=\"row\"><span class=\"col-md-4\">Ordre de tri<\/span><\/div><\/div><\/div><\/div><\/div><\/li>"");
Uncaught SyntaxError: missing ) after argument list
It's good practice to pass any PHP variable to javascript using json_encode(). Using json_encode() you'll always get a properly formatted JavaScript object with the quotes escaped.
<script>
$('#insert').click(function(){
$( "ul#list" ).append(<?php echo json_encode($card); ?>);
});
</script>
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.
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.