trying to delete multiple records in php page - javascript

I am trying below code for deleting multiple records from database. but when i open users1.php , i got below result
users1.php - javascript code below is javscript code....
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function deleteConfirm(){
var result = confirm("Are you sure to delete users?");
if(result){
return true;
}else{
return false;
}
}
$(document).ready(function(){
$('#select_all').on('click',function(){
if(this.checked){
$('.checkbox').each(function(){
this.checked = true;
});
}else{
$('.checkbox').each(function(){
this.checked = false;
});
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#select_all').prop('checked',true);
}else{
$('#select_all').prop('checked',false);
}
});
});
</script>
users1.php - php code - below is php code....
<?php
include_once('dbcontroller.php');
$query = mysqli_query($conn,"SELECT id, UserName, Type, department FROM Admin_Master";);
?>
<form name="bulk_action_form" action="users2.php" method="post" onsubmit="return deleteConfirm();"/>
<table class="bordered">
<thead>
<tr>
<th><input type="checkbox" name="select_all" id="select_all" value=""/></th>
<th>Username</th>
<th>Type</th>
<th>Department</th>
</tr>
</thead>
<?php
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
?>
<tr>
<td align="center"><input type="checkbox" name="checked_id[]" class="checkbox" value="<?php echo $row['id']; ?>"/></td>
<td><?php echo $row['UserName']; ?></td>
<td><?php echo $row['Type']; ?></td>
<td><?php echo $row['department']; ?></td>
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No records found.</td></tr>
<?php } ?>
</table>
<input type="submit" class="btn btn-danger" name="bulk_delete_submit" value="Delete"/>
</form>
Please let me know if you need more information....

remove semicolon in mysqli_query()
$query = mysqli_query($conn,"SELECT id, UserName, Type, department FROM Admin_Master";);

Related

PHP & MySQL & JS editable table won't update records

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

AJAX JSON loaded form buttons refreshes page instead on working with AJAX again

I have a strange problem here. I am processing data via AJAX from a table loaded inside while loop and when the data is successfully processed the table gets reloaded with new data via AJAX and JSON. The problem is that when the new table is loaded and I click the same submit button from any row again then this time instead of processing it via AJAX it works as a normal submit button and refreshes the page. Then when the page is refreshed the submit button works via AJAX again. Why is it not working with AJAX when the table was reloaded via AJAX after previous operation via AJAX when in both the tables the parameters used are exactly the same? My codes are below. Please tell my what's wrong here and what's the solution for this.
membership.php
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Memberships List</h3>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover table-striped" id="mbslist">
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$i = 1;
$mem = $pdo->prepare("SELECT * FROM memberships");
$mem-> execute();
while($m = $mem->fetch()){ extract($m);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
?>
<tr>
<td><?php echo $i; ?></td>
<td><span style="color: <?php echo $mem_color; ?>"><?php echo $mem_name; ?></span></td>
<td>₹<?php echo $mem_daily_capping; ?></td>
<td>₹<?php echo $mem_earn_amount; ?></td>
<td>₹<?php echo $mem_min_payout; ?></td>
<td><?php echo $mem_payout_percent; ?>%</td>
<td><?php if($mem_price == '0.00'){ echo "Free"; }else{ echo "₹$mem_price"; } ?></td>
<td><span class="<?php echo $statusColor; ?>"><?php echo ucfirst($mem_status); ?></span></td>
<td>
<form method="post" action="">
<input type="hidden" value="<?php echo $mem_id; ?>" class="memid">
<input type="hidden" value="<?php echo $status; ?>" class="status">
<input type="hidden" value="memstatus" class="type">
<?php if($mem_id != 1){ ?>
<input type="submit" class="btn <?php echo $btn; ?> mbslist" value="<?php echo ucfirst($btnVal); ?>">
<?php } ?>
Edit
</form>
</td>
</tr>
<?php $i++; } ?>
</table>
</div>
</div>
</div>
<div class="message"></div>
</div>
AJAX Code
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
processes/memberships.php
<?php
include('../../config/db.php'); include('../../functions.php');
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
Modify your processes/memberships.php with following code:
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
?>
<script>
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
</script>
Hope this might help you.
Your submit button will try to submit form normally when you click it. So just use "event.preventDefault() " as below so your button wont trigger normal form submission and now wont load the page.
$(".mbslist").click(function(event) {
event.preventDefault();
}

How to use jQuery POST instead of html form to delete table entry

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>

How to arrange the table using php, javascript

This is a php and javascript. I have a row consist of classcode, courseNumber,courseDescription,units,time,days,room the problem is I could not arrange it. It displays all data in the column of courseDescription. Below is the picture what it looks like now and how I want it to be.
[https://plus.google.com/u/0/112172241812600096315/posts/Du8f6rHsEtY?pid=6147544934724622242&oid=112172241812600096315][1]
javascript
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function()
{
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if(faq_search_input.length>3)
{
$.ajax({
type: "GET",
url: "search.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response)
{
$('#searchresultdata').html(server_response).show();
$('span#faq_category_title').html(faq_search_input);
if ($('input#faq_search_input').hasClass("loading")) {
$("input#faq_search_input").removeClass("loading");
}
}
});
}return false;
});
});
home.php
<div id="SubjectOffering" class = "listTable" >
<p><h3> Subject Offering </h3> </p>
<p>
<div class = "searchBar">
<form id="searchbox" action="#" onsubmit="return false;">
<!-- The Searchbox Starts Here -->
<input name="query" type="text" id="faq_search_input" />
<!-- The Searchbox Ends Here -->
</form>
</div>
</p>
<p>
<table>
<tr>
<td>Class Code</td>
<td>Course Number</td>
<td>Course Description</td>
<td>Time</td>
<td>Days</td>
<td>Room</td>
</tr>
<tr>
<td></div></td>
<td></td>
<td><div id="searchresultdata" class="faq-articles"> </td>
<td> </td>
<td> </td>
<td></td>
<td> </td>
</tr>
</table>
search.php
<?php
include_once ('connections.php');
if(isset($_GET['keyword'])){
$keyword = trim($_GET['keyword']) ;
$keyword = mysqli_real_escape_string($dbc, $keyword);
$query = "select courseCode,classcode,courseDescription,time,day,room from class where classcode like '%$keyword%' or courseDescription like '%$keyword%' or courseCode like '%$keyword%' or time like '%$keyword%'
or day like '%$keyword%' or room like '%$keyword%'";
//echo $query;
$result = mysqli_query($dbc,$query);
if($result){
if(mysqli_affected_rows($dbc)!=0){
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<p> <b>'.$row['classcode'].'</b> '.$row['courseCode']. '</b>'.$row['courseDescription'].'</b> '.$row['time'].'</b> '.$row['day'].'</b> '.$row['room'].'</p>';
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
}else {
echo 'Parameter Missing';
}
?>
Your code has few html tag errors like unused tags are there. I just revised your code. Please verify if you found any errors still just let me know.
Your JAVASCRIPT / JQUERY code should be as the following:
/**
* #description: Update result when user searches.
* #author Vivek Keviv
* #params none
* #return none
*/
$ (document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length>3) {
$.ajax({
type: "GET",
url: "search.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').html(server_response).show();
$('span#faq_category_title').html(faq_search_input);
if ($('input#faq_search_input').hasClass("loading")) {
$("input#faq_search_input").removeClass("loading");
}
}
});
}
return false;
});
});
Your HTML code should be as the following:
<div id="SubjectOffering" class="listTable">
<p>
<h3>Subject Offering</h3>
</p>
<div class="searchBar">
<form id="searchbox" action="#" onsubmit="return false;">
<!-- The Searchbox Starts Here -->
<input name="query" type="text" id="faq_search_input" />
<!-- The Searchbox Ends Here -->
</form>
</div>
<div id="searchresultdata" class="faq-articles">
<table>
<tr>
<th>Class Code</th>
<th>Course Number</th>
<th>Course Description</th>
<th>Time</th>
<th>Days</th>
<th>Room</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
Your PHP code should be as the following:
<?php
include_once ('connections.php');
if (isset($_GET['keyword'])) {
$keyword = trim($_GET['keyword']) ;
$keyword = mysqli_real_escape_string($dbc, $keyword);
$query = "select courseCode,classcode,courseDescription,time,day,room from class where classcode like '%$keyword%' or courseDescription like '%$keyword%' or courseCode like '%$keyword%' or time like '%$keyword%'
or day like '%$keyword%' or room like '%$keyword%'";
//echo $query;
$result = mysqli_query($dbc,$query);
if ($result) {
if (mysqli_affected_rows($dbc)!=0) { ?>
<table>
<tr>
<th>Class Code</th>
<th>Course Number</th>
<th>Course Description</th>
<th>Time</th>
<th>Days</th>
<th>Room</th>
</tr>
<?php while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) { ?>
<tr>
<td><?php echo $row['classcode']; ?></td>
<td><?php echo $row['courseCode']; ?></td>
<td><?php echo $row['courseDescription']; ?></td>
<td><?php echo $row['time']; ?></td>
<td><?php echo $row['day']; ?></td>
<td><?php echo $row['room']; ?></td>
</tr>
<?php } ?>
</table>
<?php } else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
} else {
echo 'Parameter Missing';
}
?>
Thanks & Regards,
Vivek

Error in Passing PHP value to another page using JavaScript

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; ?>'">

Categories

Resources