onclick event inside table and foreach loop - javascript

I want to allow clicking on a whole host table in foreach loop in codeigniter. For some reason, the code does not work for me. Do you have an idea how to fix it?
Thanks in advance
<table class="table table-hover">
<thead>
<tr>
<th>השולח</th>
<th>נשלחה בתאריך</th>
<th>נושא ההודעה</th>
<th>תוכן ההודעה</th>
</tr>
</thead>
<tbody>
<?php foreach ($messages->result() as $row)
{
?>
<script type="text/javascript">
function newDoc() {
window.location.assign("<?php echo base_url();?>/read_messages/<?php echo $row->id;?>")
}
</script>
<?php
echo "<tr>";
echo "<td>".$row->author. "</td>";
echo "<td>".$row->posted_in. "</td>";
echo "<td>".$row->title. "</td>";
echo "<td>".$row->body. "</td>";
?>
onclick="newDoc()";
<?php
echo "</tr>";
}
?>
</tbody>
</table>
</div>

As I understand your question you want fetch click on every row. then your code should be as:
Your Script should be out side
<script type="text/javascript">
function newDoc(id) {
window.location.assign("<?php echo base_url();?>/read_messages/"+id);
}
</script>
<?php foreach ($messages->result() as $row)
{
echo "<tr onclick='newDoc(".$row->id.")'>";
echo "<td>".$row->author. "</td>";
echo "<td>".$row->posted_in. "</td>";
echo "<td>".$row->title. "</td>";
echo "<td>".$row->body. "</td>";
echo "</tr>";
}
?>

You have to assign onClick="newDoc" to html element like
<table onClick="newDoc()">

You have to issues, one your newDoc() function is not assigned to element and two you want create the newDoc function once and only once passing in the $row->id so that its affect changes for each <tr>
<script type="text/javascript">
function newDoc(rowId) {
window.location.assign("<?php echo base_url();?>/read_messages/" + rowId);
}
</script>
<?php
foreach ($messages->result() as $row) {
echo "<tr onlick='newDoc(<?php echo $row->id ?>)'>";
echo "<td>".$row->author. "</td>";
echo "<td>".$row->posted_in. "</td>";
echo "<td>".$row->title. "</td>";
echo "<td>".$row->body. "</td>";
echo "</tr>";
}
?>

Related

Popup won't appear when clicked inside a table button

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', ...)
}

How to generate ids for tables made by php

I am trying to create a page to allow toggling on and off certain forums in website, created from raw data in an SQL server. However I need each to have an individual ID so I can show/hide them based on user preference. I am not sure how to go about it. Here is my existing code, disregard the connection values, I am hiding them on purpose. thanks.
$db_host = "host";
$db_username = "username";
$db_pass = "pass";
$db_name = "name";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $db->query('SELECT p.name, p.company, o.prodtype AS Type
FROM ownedproducts AS o
JOIN product as p ON p.productID = o.productID
WHERE o.usersID = 2');
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title> User Forum Selection </title>
</head>
<body>
<div>
<input type="text" id="userid">
</div>
<div>
<hr>
<table id=table border = '2'>
<tr id=table-row>
<th id=table-header>Name</th>
<th id=table-header>Company</th>
<th id=table-header>Type</th>
</tr>
<?php
while ($row = $query->fetch())
{
echo "<tr id=table-row >";
echo "<td>" . $row['name'] ."</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}
?>
</table>
</div>
</body>
</html>
What about using the product id ? That sounds logical here.
Select it :
$query = $db->query('SELECT p.productID, p.name, p.company, o.prodtype AS Type ...
Then use it in your rows :
while ($row = $query->fetch())
{
echo "<tr id='table-row-" . $row['id'] . "' >";
echo "<td>" . $row['name'] ."</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}
Always use single and double quote in id as (id=' ', id=" ")
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title> User Forum Selection </title>
</head>
<body>
<div>
<input type="text" id="userid">
</div>
<div>
<hr>
<table id=table border = '2'>
<tr id=table-row>
<th id=table-header>Name</th>
<th id=table-header>Company</th>
<th id=table-header>Type</th>
</tr>
<?php
while ($row = $query->fetch())
{
echo "<tr id=table-row >";
echo "<td>" . $row['name'] ."</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}
?>
</table>
</div>
</body>
</html>
use it in your rows :
<?php
foreach( $query->fetch() as $rows=> $row)
{
echo "<tr id='table-row-'.$rows >";
echo "<td>" . $row[or</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}
?>
I'd probably do it in a foreach and use the key.
foreach( $query->fetch() as $key => $row)
{
echo "<tr id='table-row-'.$key >";
echo "<td>" . $row['name'] ."</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}

Inline JavaScript function within PHP Tag

I am running this code in a PHP file
<?php
if(empty($item)){
echo "Your cart is empty";
}
else{
echo '<table id="cart_table"><tr><th>Item</th><th>Price</th><th></th></tr>' ;
for($i = 0;$i< count($item);$i++){
if(!empty($item[$i])){
$numRow++;
echo '<tr><td>' . "<img src = 'images/$photo[$i].jpg'>" .'</td>';
echo '<td>' .'$' . $item[$i] . '</td>';
echo '<td>' . '<button id= "btn" onclick = "function(){
<script type="text/javascript">
document.getElementById("cart_table").deleteRow('. $numRow .');
}"> Remove</button>'.'</tr>' ;
}
}
echo '</table>';
}
?>
Please consider these lines of code only from the above snippet:
echo '<td>' . '<button id= "btn" onclick = "function(){
<script type="text/javascript">
document.getElementById("cart_table").deleteRow('. $numRow .');
}"> Remove</button>'.'</tr>' ;
}
The result of this code is:
The result I am trying to achieve is:
Is it possible to achieve this result? The result is going to be a button with the label "Remove" and with the onClick property that calls a INLINE(I know it's bad practice, but I have a good reason for it) function which executes some lines of code.
Try not to mix up HTML and PHP together, if there is a need to mix HTML and PHP, try in proper formatting.
<?php
if(empty($item)):
?>
<span>Your cart is empty</span>
<?php
else:
?>
<table id="cart_table">
<tr>
<th>Item</th>
<th>Price</th>
<th></th>
</tr>
<?php
for($i = 0;$i< count($item);$i++):
if(!empty($item[$i])):
$numRow++;
?>
<tr>
<td><img src ='images/<?php echo $photo[$i].jpg; ?>'/></td>
<td>$<?php echo $item[$i]; ?></td>
<td><button id= "btn" onclick = "deleteFromCart('<?php echo $numRow; ?>')"> Remove</button></td>
</tr>
<?php
endif;
endfor;
?>
</table>
<?php
endif;
?>
<script>
function deleteFromCart(rowToDelete){
document.getElementById("cart_table").deleteRow(rowToDelete);
}
</script>

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>

How to display another table by clicking a button that is inside the table?

<html>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." />
<input type="submit" value="search" />
</form>
</body>
</html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: middle;
}
</style>
<script type="text/javascript">
function showHide(id) {
if (document.getElementById(id).style.display == 'none') {
document.getElementById(id).style.display = '';
}
else {
document.getElementById(id).style.display = 'none';
}
}
</script>
</head>
<body>
<table border="1">
<?php
mysql_connect("localhost","root","") or die("could not connect");
mysql_select_db("vauban") or die("could not find database");
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM info3 WHERE FirstName LIKE '%$searchq%' OR LastName LIKE '%$searchq%'") or die("could not search!");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}else{
while($row = mysql_fetch_array($query)) {
$id = $row['Id'];
echo"<td>". $row['Id']."</td>";
echo"<td>". $row['FirstName']."</td>";
echo"<td>". $row['LastName']. "</td>";
echo"<td>". $row['PhoneNumber']. "</td>";
echo"<td> <button onclick=\"showHide('id'); return false;\">". $row['CompanyName']. "</button></td>";
echo"<td> <a href ='view.php?Id=$id'>Edit</a>";
echo"<td> <a href ='del.php?Id=$id'><center>Delete</center></a>";
echo "</tr>";
$CompanyName=$row['CompanyName'];
}
}
}
?>
</table>
<script type="text/javascript">
function showHide(id) {
$CompanyName=$row['CompanyName'];
if ($CompanyName = "Company A") {
<?php
echo "<table id='test1' style='width:50%' align='right'>";
include("db.php");
$result=mysql_query("SELECT * FROM company where no = '1'");
while($test = mysql_fetch_array($result))
{
$id = $test['No'];
echo "<th rowspan='1'>Company name</th>";
echo "<td colspan='3'>". $test['CompanyName']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Location</th>";
echo "<td colspan='3'>". $test['Location']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Found</th>";
echo "<td colspan='3'>". $test['Found']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Website</th>";
echo "<td colspan='3'>". $test['Website']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th rowspan='3'>Contact</th>";
echo "<th>Email</th>";
echo "<td colspan='3'>". $test['Email']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Phone</th>";
echo "<td colspan='3'>". $test['Phone']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Fax</th>";
echo "<td colspan='3'>". $test['Fax']. "</td>";
echo "</tr>";
echo "<br>";
}
mysql_close($conn);
?>
</table>
}
else if ($CompanyName = "Company B") {
<?php
echo "<table id='test2' style='width:50%' align='right'>";
include("db.php");
$result=mysql_query("SELECT * FROM company where no = '2'");
while($test = mysql_fetch_array($result))
{
$id = $test['No'];
echo "<th rowspan='1'>Company name</th>";
echo "<td colspan='3'>". $test['CompanyName']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Location</th>";
echo "<td colspan='3'>". $test['Location']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Found</th>";
echo "<td colspan='3'>". $test['Found']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Website</th>";
echo "<td colspan='3'>". $test['Website']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th rowspan='3'>Contact</th>";
echo "<th>Email</th>";
echo "<td colspan='3'>". $test['Email']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Phone</th>";
echo "<td colspan='3'>". $test['Phone']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Fax</th>";
echo "<td colspan='3'>". $test['Fax']. "</td>";
echo "</tr>";
echo "<br>";
}
mysql_close($conn);
?>
</table>
}
else if ($CompanyName= "Company C") {
<?php
echo "<table id='test3' style='width:50%' align='right'>";
include("db.php");
$result=mysql_query("SELECT * FROM company where no = '3'");
while($test = mysql_fetch_array($result))
{
$id = $test['No'];
echo "<th rowspan='1'>Company name</th>";
echo "<td colspan='3'>". $test['CompanyName']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Location</th>";
echo "<td colspan='3'>". $test['Location']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Found</th>";
echo "<td colspan='3'>". $test['Found']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Website</th>";
echo "<td colspan='3'>". $test['Website']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th rowspan='3'>Contact</th>";
echo "<th>Email</th>";
echo "<td colspan='3'>". $test['Email']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Phone</th>";
echo "<td colspan='3'>". $test['Phone']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Fax</th>";
echo "<td colspan='3'>". $test['Fax']. "</td>";
echo "</tr>";
echo "<br>";
}
mysql_close($conn);
?>
</table>
}
else if ($CompanyName = "Company D") {
<?php
echo "<table id='test4' style='width:50%' align='right'>";
include("db.php");
$result=mysql_query("SELECT * FROM company where no = '4'");
while($test = mysql_fetch_array($result))
{
$id = $test['No'];
echo "<th rowspan='1'>Company name</th>";
echo "<td colspan='3'>". $test['CompanyName']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Location</th>";
echo "<td colspan='3'>". $test['Location']."</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Found</th>";
echo "<td colspan='3'>". $test['Found']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Website</th>";
echo "<td colspan='3'>". $test['Website']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th rowspan='3'>Contact</th>";
echo "<th>Email</th>";
echo "<td colspan='3'>". $test['Email']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Phone</th>";
echo "<td colspan='3'>". $test['Phone']. "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Fax</th>";
echo "<td colspan='3'>". $test['Fax']. "</td>";
echo "</tr>";
echo "<br>";
}
mysql_close($conn);
?>
}
else {
alert("No such company exist...");
}
}
</script>
</body>
</html>
My table:
and what I want to display when I click on one of the button:
I just want to display another table when I click on one of the column and it has to be accurate (e.g. click Company C to get information of Company C).
Tried using function() ---> fail
Tried using if else ---> fail
You may want to use AJAX in order to achieve what you want.
Reminder: mysql_* is already deprecated, so you should consider mysqli_* instead.
First is, you need to list down your data in a table from info3 table, assuming that company table has CompanyName column in order to connect it to your info3 table's CompanyName column.
echo '<td> <button class="company_button">'.$row['CompanyName'].'</button></td>';
And create a div space for returned data of the clicked button.
<div id="company_desc_div"></div>
Then we can create a script using jQuery (javascript library) which you can download here.
$(document).on("click", ".company_button", function(){ /* WHEN A BUTTON IS CLICKED */
var company_desc = $(this).text(); /* GET WHAT COMPANY IS IT */
$.ajax({ /* START AJAX */
type: "POST", /* METHOD TO USE TO PASS THE DATA */
url: "get_company_info.php", /* FILE WHERE WE WILL PROCESS THE PASSED ON DATA */
data: { "company_desc": company_desc }, /* DATA TO BE PASSED ON */
success: function(result){ /* GET THE RETURNED DATA FROM get_company_info.php */
$("#company_desc_div").html(result); /* PUT THE RETURNED DATA TO company_desc_div DIV */
}
});
});
As you might notice, we pass the data of the clicked button to get_company_info.php, so lets create that file:
<?php
/* ESTABLISH YOUR CONNECTION */
$con = new mysqli("localhost", "root", "", "vauban");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT CompanyName, Location, Found, Website, Email, Phone, Fax FROM company WHERE CompanyName = ?")){ /* PREPARE THE STATEMENT */
$stmt->bind_param("s", $_POST["company_desc"]); /* BIND THE PASSED ON DATA TO THE SELECT QUERY */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($companyname, $location, $found, $website, $email, $phone, $fax); /* BIND THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULTS */
/* WHAT YOU ECHO IS WHAT WILL BE RETURNED TO THE AJAX REQUEST */
echo '<table>
<tr>
<th>Company name</th>
<td colspan="3">'.$companyname.'</td>
</tr>
<tr>
<th>Location</th>
<td colspan="3">'.$location.'</th>
</tr>
<tr>
<th>Found</th>
<td colspan="3">'.$found.'</td>
</tr>
<tr>
<th>Website</th>
<td colspan="3">'.$website.'</td>
</tr>
<tr>
<th rowspan="3">Contact</th>
<th>Email</th>
<td>'.$email.'</td>
</tr>
<tr>
<th>Phone</th>
<td colspan="3">'.$phone.'</td>
</tr>
<tr>
<th>Fax</th>
<td colspan="3">'.$fax.'</td>
</tr>
</table>';
$stmt->close();
} /* END OF PREPARED STATEMENT */
?>
What we echo from this file is what will be returned to the AJAX request.

Categories

Resources