I have an HTML which displays data from a database table. There'a checkbox field, which stores id of the user. And when I click on a row, that ID has to be passed to another page using a JavaScript function. But I have encountered a few errors. I don't know where I went wrong.
This is my Javascript function. It is used to make the table rows clickable. SO when I click on a row, the corresponding ID is passed to editgroup.php page.
<script>
$('table.table tbody tr').click(function(event)
{
if(event.target.type === 'checkbox')
{
event.preventdefault()
}
else
{
window.location='edituser.php?val=<?php echo $id; ?>';
}
});
</script>
Below given is my table:
<table id="edituser" class="clickable"
<thead>
<th></th>
<th>UserID</th>
<th>Username</th>
</thead>
<tbody>
<?php
for($i=0; $i<$x; $i++)
{
$id= $val_array[$i]['id'];
$userName= $val_array[$i]['userName'];
?>
<tr>
<td class="text-center"><input type="checkbox" value="<?php echo $id; ?>"></td>
<td><?php echo $id; ?></td>
<td><?php echo $userName; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
you have to make some change
First in your tr add id like this
<?php
for($i=0; $i<$x; $i++)
{
$id= $val_array[$i]['id']; //data from database
$userName= $val_array[$i]['userName']; //data from database
?>
<tr id="<?php echo $id;?>"> <!-- add id here -->
<td ><input type="checkbox" value="<?php echo $id; ?>"></td>
<td><?php echo $id; ?></td>
<td><?php echo $userName; ?></td>
</tr>
<?php } ?>
now your JS
<script>
$('table.clickable tbody tr').click(function(event){
if(event.target.type === 'checkbox'){
event.preventdefault()
}else{
var val = $(this).attr('id');
window.location='edituser.php?val='+val;
}
}); </script>
Your Javascript will be
$('table.table tbody tr').click(function(event){
if(event.target.type === 'checkbox'){
event.preventdefault()
}else{
var value = (this).find("input[type='checkbox']").val(); /* Get value from clicked tr Checkbox */
window.location.replace('edituser.php?val='+value); /* Pass the value */
}
});
Create new function with dynamic id for your table row
<tr onclick="edit_user(<?php echo $id;?>)" >
....
</tr>
Then you can find your row of where you have to click
<script>
function edit_user(user_id) {
if(user_id != '') {
window.location='edituser.php?val='+user_id;
}
}
</script>
Or else
This is more even simple your code.
<input type="checkbox" value="<?php echo $id; ?>" onclick="document.location.href='edituser.php?val=<?php echo $id; ?>'">
Related
So I'm trying to use a table to update some records in my database but each time I click on update it won't work and it won't do anything. A part of the code below was found in an another topic but it was incomplete so I added some other things.
Js script
$(function(){
$("#loading").hide();
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
This is the table fetching the rows from the database, however everything works besides updating.
HTML & PHP
<form method="post" action="update.php">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-striped table-dark">
<tr bgcolor="#df4662" style="color:#FFFFFF;">
<td>ID</td>
<td>Nickname</td>
<td>Name</td>
<td>Rank</td>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td contenteditable="true" id="id:<?php echo $row["id"]; ?>"><?php echo $row["id"]; ?></td>
<td contenteditable="true" id="username:<?php echo $row["username"]; ?>"><?php echo $row["username"]; ?></td>
<td contenteditable="true" id="name:<?php echo $row["steamid"]; ?>"><?php echo $row["steamid"]; ?></td>
<td contenteditable="true" id="ranks:<?php echo $row["ranks"]; ?>"><?php echo $row["ranks"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</form>
After a few errors I've been able to have a clean error_logs, but now I don't get any error even after pressing the update button.
update.php
<?php
include '../database.php'
?>
<?php
if(!empty($_POST))
{
foreach($_POST as $field_name => $val)
{
$field_id = strip_tags(trim($field_name));
$split_data = explode(':', $field_id);
$id = $split_data[1];
$field_name = $split_data[0];
if(!empty($id) && !empty($field_name) && !empty($val))
{
$affected_rows = mysqli_query($mysqli,"UPDATE users SET $field_name = '$val' WHERE id = $id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Request";
}
}
}
else {
echo "Invalid Requests";
}
?>
EDIT: Thanking Sam now the problem is just that the record won't update at all
I am trying to delete the table entry without opening the .php file using jQuery post.
The whole thing works without problems when I just use the usual html post form.
The alert(data) does not trigger, it only adds ".../?player_id_del=1" or whatever ID click into the URL.
What am I doing wrong?
Here is some of my index.php, i get the whole data from a database:
<table class = "table table-hover">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr>
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<form id="del-form">
<div>
<input type="number" id="player_id_del" name="player_id_del" value="<?php echo htmlspecialchars($player["PLAYER_ID"]); ?>" />
</div>
<div>
<button type="submit" id="submit-btn" class="btn btn-danger">Delete</button>
</div>
</form>
<script>
$("#submit-btn").click(function(){
$.post("deletePlayer.php", $("#del-form").serialize() , function(data) {
alert(data);
});
});
</script>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
Here is my deletePlayer.php:
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
echo "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
echo "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
?>
Thank You in advance for any help!
By default jQuery's click event reload the document so, you should try using,
$("#submit-btn").click(function(e){
e.preventDefault();
e.stopPropagation();
});
Also instead of $.post, try using $.ajax
There are many issues in your code
E.g IDs for form and delete input button are repeating (id of element should not be same it should be unique),
The following code is the tested and working.
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
$response = array();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
$response["success"] = 1;
$response["id"] = $player_id;
$response["message"] = "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
$response["success"] = 0;
$response["message"]= "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
echo json_encode($response);
?>
<table class = "table table-hover" id="mPlayersTabel">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr id= "<? echo $player["PLAYER_ID"]; ?>">
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<div>
<button type="submit" player-id="<? echo $player["PLAYER_ID"]; ?>" class="btn btn-danger" >Delete</button>
</div>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
<script>
$(document).ready(function(){
$(".btn-danger").on("click touchend" , function(){
var id = $(this).attr("player-id");
$.ajax({
url: 'deletePlayer.php',
type: 'POST',
data: {
player_id_del: id
},
dataType: 'json',
success: function (response) {
//Add this line and try
response = JSON.parse(JSON.stringify(response));
alert(response['message']);
switch (response['success']) {
case 1:
$("#mPlayer" + response['id']).remove();
break;
}
}
});
});
});
</script>
I have an admin panel that I am creating. I have a left panel section and then the right side which shows the div when the panel button is clicked. I created a fiddle to show what it looks like and to help me explain this...
https://jsfiddle.net/jq8c51c9/
In the Fiddle it works just like it should, but I took out all of my php. The problem is around the Announcements div, it shows the div for the League Dues under it. Also once you click on announcements and then click on another panel button, if I click on Announcements again the only thing that will show up is this..
Announcements Current Announcements
League Dues
Again this is NOT doing this in the Fiddle.
Here is the full code for the area that the issue resides in. I have been stuck on this forever and cannot figure out why I am having difficulties with only these two divs.
Does anyone see what it is that I am doing wrong?
Announcements
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
$user_stmt->store_result();
$user_result = array();
//while ($user_row = $user_stmt->fetch()) {
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
<?php
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
</table>
<?php
}
}
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}
?>
</div>
<div id='dues'>League Dues</div>
</div>
You have an error when building the announcement-table.
The closing </table> tag is inside the while loop, so the html will be screwed up, making everything after the closed table disappear.
So change the while loop to:
....
<?php
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
</table>
<?php
....
Anyway, I recommend to build your html first in a variable and echo it out later alltogether. That makes cleaner code and reduces risk of inconsitency of html tags. When using with HEREDOC you even don't have to bother about quotes.
In your case that could for example look like that:
<?php
$table_head = <<<EOT
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
EOT;
$table_content = "";
while ($row = $stmt->fetch()) {
$table_content.= <<<EOT
<tr>
<td>$announcements_id</td>
<td>$announcements_username</td>
<td>$announcements_messages</td>
<td>$announcements_date</td>
</tr>
EOT;
}
$announcement_table = "<table>".$table_head.$table_content."</table>";
echo $announcement_table;
I've got the following table on a webpage:
<table class="table table-striped table-condensed">
<thead>
<tr>
<center><th>Name</th><th>Rank</th><th>MOS</th><th>Tag</th><th>MOSTs</th><th>Prom. Date</th><th>DI</th><th>CMO</th><th>MCRC</th><th>Medals</th><th>Leave</th></center>
</tr>
</thead>
<tbody>
<?php
$rank = 'O-10';
$result->execute();
while($row = $result->fetch()) {
?>
<tr>
<td id="habbo_name:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['habbo_name']);?></td>
<td id="rank:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['rank']);?></td>
<td id="rating:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['rating']);?></td>
<td id="tag:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['tag']);?></td>
<td id="asts:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['asts']);?></td>
<td id="promotion_date:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['promotion_date']);?></td>
<td id="rdc_grade:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['rdc_grade']);?></td>
<td id="cnl_trainings:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['cnl_trainings']);?></td>
<td id="mcrc:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['mcrc']);?></td>
<td id="medals:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['medals']);?></td>
<td id="leave:<?php echo htmlspecialchars($row['user_id']); ?>" contenteditable="true"><?php echo htmlspecialchars($row['leave']);?></td>
</tr>
<?php
}
?>
</tbody>
</table>
I have this code which sends a request to ajax.php whenever a td is clicked:
<script type="text/javascript">
$(function(){
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = '$(this).text()' ;
$.post('ajax.php' , field_userid + "=" + value, function(data){
});
});
});
</script>
ajax.php:
<?php
include 'functions/user.php';
if(!empty($_POST))
{
foreach($_POST as $field_name => $val)
{
$field_userid = strip_tags(trim($field_name));
$split_data = explode(':', $field_userid);
$user_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($user_id) && !empty($field_name))
{
$query = "UPDATE `personnel` SET $field_name = '$val' WHERE user_id = $user_id";
$result = $con->prepare($query);
$result->execute();
} else {
echo "Invalid Requests";
}
}
} else {
echo "Invalid Requests";
}
?>
The problem I have is with 3 of the fields - MCRC, Medals and Leave - the others all update fine.
The MCRC field will either be empty or contain the + symbol. Using firebug, this is the POST request when trying to send a +:
As you can see, the + is removed in the parameters. The same goes for medals.
Leave seems to have a different issue. The parameters are fine but the database is not updated with the [TEST]
If anyone could explain a way for me to send symbols/see what's going wrong with leave that would be great. Thanks.
Got it working by changing
var value = $(this).text();
to
var value = encodeURIComponent($(this).text());
I have my database table named material
material:
mat_id mat_name status
1 bolts
2 steel approved
How can I make my button or maybe href link disable when status = 'approved'
on my html table?
like:
option mat_id material name
show button 1 bolts
no button 2 steel
my code for html/php:
<?php
$resource=mysql_query("Select * from material",$con);
while($result2=mysql_fetch_array($resource))
{
?>
<tr>
<th>option</th>
<th>mat_id</th>
<th>material name</th>
</tr>
<tr>
<td align="center">
<?php
$id = $rows['reqraw_id'];
if($rows['status']=="")
{
echo '<a href="addstockout.php?id=$id" > Update </a>';
} ?>
</td>
<td><?php echo $result2['mat_id']; ?></td>
<td><?php echo $result2['mat_name']; ?></td>
</tr>
<?php };?>
There is a problem on this line
echo '<a href="addstockout.php?id=$id" > Update </a>';
It doesn't get the id array from the db.
...
<?php if($result2['status'] == 'approved') { ?>
<td><button disabled="true">Button</button></td>
<?php
} else{ ?>
<td><button>Button</button></td>
<?php } ?>
...
if($result2['status']=="" OR $result2['status']===NULL)
{
echo '<button type="button">Click Me!</button>';
}else{
echo '<button type="button" disabled>Click Me!</button>';
}
<td><?php echo ($result2['status']===NULL)?"button here":"disabled"; ?></td>
I think this should do it:
Instead of
<td>button</td>
put:
<?php
echo '<td><button ';
if(!($result2['status']==="approved"))
{
echo 'disabled="true"';
}
echo '>Click</button></td>';
?>