I tried to update 1 row in table with ajax triggered by onchange dropdown, I succeed update data but it updating all data in my table.
so how I can get unique value (eg :User ID) to pass it from ajax to my php so i can update it only 1 row?
here's my code :
my table (transactions.php)
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();">
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and here my ajax
function updatetransactions(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:"status="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
my updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$penjualan_id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
I assume that you update all of your rows in your database, with no WHERE condition. In your script, lets also get the corresponding id of that row in your database.
Lets assign first the id for each table row:
while($data1 = mysqli_fetch_array($query)){
?>
<tr id="<?=($data1['user_id'])?>">
Then, lets change how you trigger your javascript. Lets first change the <select> field:
<select name="pilihstatus" id="pilihstatus" class="pilihstatus">
Then, get the corresponding id using the script below:
$(".pilihstatus").change(function(){
var elem = $(this),
selecteditem = elem.val(),
id = elem.closest('tr').attr('id');
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data: {'status':selecteditem, 'id':id},
success:function(data){
alert('Successfully updated mysql database');
}
});
});
And on your updatestatustransaksi.php file (please use prepared statement):
$stmt = $koneksi->prepare("UPDATE `konf_transf` SET `status` = ? WHERE `id` = ?");
$stmt->bind_param("si", $_POST['selecteditem'], $_POST['id']);
$stmt->execute();
$stmt->close();
Try adding data_id attribute to select
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();" data_id='<?php echo $data1['usr_id']; ?>'>
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and get that data_id value in your function
function updatetransactions(){
var status = $('select option:selected').text();
var status = $('select').attr('data_id');
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:{'status'=status,'id'=id}
success:function(data){
alert('Successfully updated mysql database');
}
});
}
and at your updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$id = $_POST["id"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
Have you initialised $penjualan_id? I think you need to initialise it like this:
$penjualan_id=$_SESSION['user_id']
Related
Im trying to dynamically allow the user to change a user role by using a select tag within a table which, when change triggers an event, record the changes in JQuery and send the changes to PHP via AJAX. From the image attached, the only select tag which fires an event is the one in the first row of the table shown. Any changes made to other rows does not fired an event as shown by one of the images with the console.log information. I am trying to allow whoever has the rights to change a specific user role by selecting the adajacent select option within the same table row which is send via AJAX to change the field in the database. I have posted this question before however Wesley Smith recommended I do a new post. Anyone please feel free to comment.
<?php
require_once('../../private/initialize.php');
require_login();
$admins = find_all_admins();
?>
<?php
if(isset($_SESSION['message']) )
{
echo "<div> </div><h5 style=\"color: #08ff00\">". $_SESSION['message'] ."</h5> </div>";
}
unset($_SESSION['message']);
//if(isset($SESSION['image_msg']))
//{
// echo "<div> </div><h5 style=\\" . $_SESSION['image_msg'] . "</#ffffff> </div>";
//}
?>
<form action="" method='post'>
<table class="table table-bordered table-hover">
<!-- <div id="bulkOptionContainer" class="col-xs-4">-->
<!---->
<!-- <select class="form-control" name="bulk_options" id="">-->
<!-- <option value="">Select Options</option>-->
<!-- <option value="published">Publish</option>-->
<!-- <option value="draft">Draft</option>-->
<!-- <option value="delete">Delete</option>-->
<!-- <option value="clone">Clone</option>-->
<!-- </select>-->
<!---->
<!-- </div>-->
<div class="col-xs-4" id="addnew" >
<!-- <input type="submit" name="submit" class="btn btn-success" value="Apply">-->
<a class="btn btn-primary" href="staff.php?source=add_staff">Add New</a>
</div>
<thead>
<tr>
<!-- <th><input id="selectAllBoxes" type="checkbox"></th>-->
<th>Image</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Role</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while ($all_admins = mysqli_fetch_assoc($admins)) { ?>
<tr>
<td><img src="<?php echo url_for('../images/staff/'.$all_admins['image'])?>" onerror="this.src='<?php echo url_for('../images/staff/profile.jpg') ?>'" style="border:1px solid #ddd;border-radius:2px; box-shadow: #4a5f63; height: 70px;width: 70px"></td>
<td><?php echo h($all_admins['first_name']) ?></td>
<td><?php echo h($all_admins['last_name']) ?></td>
<td><a class='btn btn-info' href="staff.php?source=show_staff&staff_id=<?php echo h($all_admins['id']) ?>"> <?php echo h($all_admins['email']) ?> </a></td>
<td>
<?php
$role = $all_admins['role'];
switch ($role){
case 'DE':
echo "Data Entry";
break;
case 'GU':
echo "General User";
break;
default:
echo "Administrator";
break;
}
?>
<span>
<select class="urole" name="role[]">
<option value="Admin" <?php echo ($role == 'Admin')?'selected':'' ?> >Admin</option>
<option value="DE" <?php echo ($role == 'DE')?'selected':'' ?> >Data Entry</option>
<option value="GU" <?php echo ($role == 'GU')?'selected':'' ?> >General User</option>
</select>
</span>
</td>
<td><a class='btn btn-info' href="staff.php?source=edit_staff&staff_id=<?php echo h($all_admins['id']) ?>">Edit</a></td>
<form method="post">
<input type="hidden" name="post_id" value="<?php //echo $post_id ?>">
<?php
echo '<td><input class="btn btn-danger" type="submit" name="delete" value="Delete"></td>';
?>
</form>
</tr>
<!---->
<!-- <td><input class='checkBoxes' type='checkbox' name='checkBoxArray[]' value='-->
<?php } //echo $post_id; ?><!--'></td>-->
<?php
mysqli_free_result($admins);
// echo "<td><a rel='$post_id' href='javascript:void(0)' class='delete_link'>Delete</a></td>";
// echo "<td><a onClick=\"javascript: return confirm('Are you sure you want to delete'); \" href='posts.php?delete={$post_id}'>Delete</a></td>";
// echo "<td><a href='posts.php?reset={$post_id}'>{$post_views_count}</a></td>";
// echo "</tr>";
//}
?>
</tbody>
</table>
</form>
<?php
//if (isset($_POST['delete'])) {
//
// $the_post_id = escape($_POST['post_id']);
//
// $query = "DELETE FROM posts WHERE post_id = {$the_post_id} ";
// $delete_query = mysqli_query($connection, $query);
// header("Location: /cms/admin/posts.php");
//
//
//}
//
//
//if (isset($_GET['reset'])) {
//
// $the_post_id = escape($_GET['reset']);
//
// $query = "UPDATE posts SET post_views_count = 0 WHERE post_id = $the_post_id ";
// $reset_query = mysqli_query($connection, $query);
// header("Location: posts.php");
//
//
//}
?>
<script>
$(document).ready(function ()
{
// $(".delete_link").on('click', function () {
//
//
// var id = $(this).attr("rel");
//
// var delete_url = "posts.php?delete=" + id + " ";
//
//
// $(".modal_delete_link").attr("href", delete_url);
//
//
// $("#myModal").modal('show');
//});
$('.urole').on('change',function (e){
e.preventDefault();
var val = $(".urole option:selected").val();
console.log(val);
console.log(e);
// $("#urole").on('click', function(){
// v
// });
//displayData(val);
});
$("#urole").ready(function (){
var val = $("#urole option:selected").val();
console.log(val);
//displayData(val);
});
});
function displayData(query){
$.ajax({
url:"enrolled_learners/enrol_learner_provider.php",
method:"post",
data:{query:query},
success:function (data)
{
//console.log(data);
$('#q-provider').html(data);
}
});
}
<?php
//if (isset($_SESSION['message'])) {
//
// unset($_SESSION['message']);
//
// }
?>
</script>
User Interface and Console log[enter image description here][1]
[User Interface][1]
Your selector selects all with the class urole, you just want to select the one that changed, since you're in the change handler for that element you can access it via the this keyword.
$('.urole').on('change',function (e){
e.preventDefault();
var val = this.value;
console.log(val);
console.log(e);
displayData(val);
});
I have a normal html table filled with database entries.
I got a plugin to select multiple rows in this table.
Now i want to click on a button and delete the database entry so I need to get the id out of the array and but it in my php script.
But I have not really an idea how to do it.
</div>
<table id="myTable" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM artikel;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td> <?php echo $row["id"]?></td> <?php
?> <td> <?php echo $row["artikelnummer"]?></td> <?php
?> <td> <?php echo $row["name"]?></td> <?php
?> <td> <?php echo $row["preis"]?> €</td> </tr><?php
}
}
?>
</tbody>
</table>
</div>
var $rows = [];
$(function() {
console.log( "ready!" );
// start plugin
$('#myTable').TableSelection({
sort : true, // sort or not (true | false)
status : 'multiple', // single or multiple selection (default is 'single')
}, function(obj){ // callback function return selected rows array
$rows = obj.rows;
});
});
<?php
include_once 'dbh.inc.php';
$artid = ???;
$sql = "DELETE FROM artikel WHERE id= $artid;";
mysqli_query($conn, $sql);
header("Location: ../index.php?daten=success");
You can do it with html attributes. I make a example for you with html, css and javascript.
this is your html.
<table id="tableSelected" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>1</td>
<td>1-1</td>
<td>Test</td>
<td>1</td>
</tr>
<tr data-id="2">
<td>2</td>
<td>2-1</td>
<td>Foo</td>
<td>1</td>
</tr>
</tbody>
</table>
as you can see, every "tr" tag has "data-id" attribute.
var $rows = [];
$(function() {
$('#tableSelected').TableSelection({
sort : true,
status : 'multiple',
}, function(obj) {
$.each(obj.rows, function(i, row){
var id = $('#tableSelected').RowValue(row).attr('data-id') // You can get id with this code
});
});
});
Note: https://codepen.io/yusufilkeroguz/pen/vqPgzZ you can see live preview from here :)
So I have created an HTML table with dynamic rows. On the end the every row there is a button. When that button on the particular row is clicked, the row needs to removed without page refresh.
So I'm trying to do it by changing the values of column in database on button click. There is a field named 'status' in my database, which is initially set to 'unchecked'. But when I click the button, the update query is to be triggered hence changing the 'status' field to 'checked' on that particular row, and removing that particular.
newCust.php
<table class="table table-bordered table-striped table-light table-
responsive text-nowrap">
<thead class="thead-dark">
<tr>
<th class="col"><label> nID</label></th>
<th class="col"><label> CUSTOMER NAME </label></th>
<th class="col"><label> ADDRESS </label></th>
<th class="col"><label> CITY </label></th>
<th class="col"><label> STATUS </label></th>
</tr>
</thead>
<tbody>
<?php
<!-- GETTING DATA FROM THE TABLE WHERE STATUS FIELD IS UNCHECKED -->
$query = "select * from mx_newcustomer where status = 'unchecked'";
$result = mysqli_query($db,$query);
while($res = mysqli_fetch_array($result)){
$nID = $res['nID'];
?>
<tr>
<td><?php echo $nID; ?></td>
<td><?php echo $res['customername']; ?></td>
<td><?php echo $res['address']; ?></td>
<td><?php echo $res['city']; ?></td>
<td><button type="button" id="button<?php echo $nID; ?>" class="btn btn-
dark" >Ok</button></td>
</tr>
<script>
<!-- AJAX TO UPDATE RECORDS IN THE DATABASE-->
$(document).ready(function () {
$("#button<?php echo $nID ?>").click(function(){
alert('Test');
jQuery.ajax({
type: "POST",
url: "updateCust.php",
<--TRYING TO
PASS THE CLICKED BUTTON ID. I BELIEVE THIS IS WHAT I'M DOING WRONG-->
data: {"nID":$('#button<?php echo $nID ?>').serialize()},
success: function(response)
{
alert("Record successfully updated");
}
});
});
});
</script>
updateCust.php
$db = mysqli_connect("credentials");
$nID = $_POST['nID'];
$query = "UPDATE mx_newcustomer SET status = 'checked' WHERE nID =
'$nID'";
$res = mysqli_query($db, $query);
error_reporting(E_ALL);
ini_set('display_errors','On');
I'm not getting any errors, but the update query is not being triggered either. The expected result is remove the table row whose button has been clicked, without the page being refreshed.
Don't use .serialize(), it returns a string in the form name=value. But your button doesn't have a name or value, so there's nothing to serialize.
Change it to:
data: {"nID": <?php echo $nID ?>},
To delete the row, you can use:
success: function() {
$("#button<?php echo $nID?>").closest("tr").remove();
}
I have run an SQL statement to get all the records I need to show in a HTML table.
I have then run a while loop to display the records from the database. (The code for this is below.)
<table class="projects-table">
<tr>
<th>Complete?</th>
<th>Paid?</th>
<th>Project Name</th>
<th>£ / hr</th>
<th>End Date</th>
<th>Hours Logged</th>
<th><i class="fa fa-trash"></i></th>
</tr>
<?php
$select_id_jobs = mysqli_query($mysqli, "SELECT id FROM users WHERE username='$login_user'");
while($row = mysqli_fetch_array($select_id_jobs)) {
$id_jobs = $row['id'];
}
$select_jobs_with_usrid = mysqli_query($mysqli, "SELECT * FROM jobs WHERE username_id = '$id_jobs';");
while($row = mysqli_fetch_array($select_jobs_with_usrid)) {
?>
<tr id="<?php echo $rowId; ?>">
<td>
<!-- Complete Checkbox -->
<input type="checkbox" id="<?php echo $completeCheck;?>" onclick="compTask();">
</td>
<td>
<!-- Paid checkbox -->
<input type="checkbox" onclick="paidTask()">
</td>
<td>
<?php echo $row['project_title']; ?>
</td>
<td>
<?php echo $row['cost_hour']; ?>
</td>
<td>
<?php echo $row['completion_date']; ?>
</td>
<td>
<?php echo $row['time_spent']; ?>
</td>
<td>
<div class="delete-btn"><a onclick="deleteTask()">DELETE</a></div>
</td>
</tr>
<?php } ?>
</table>
As you can see from the checkbox for completing a task. What I want to do is use javascript so that when the checkbox is checked the text from the other records turns green.
I have included the javascript I am trying to use below. I don't know why but I can't access the inputs ID in order to change the css.
<script>
function compTask() {
if (document.getElementById("<?php echo 'complete-' . $row['id'] ?>").checked == true) {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "green";
alert("hello");
} else {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "black";
}
}
Okay easy way to do that is to print id as parameter in js function
something like that:
<input type="checkbox" id="<?php echo $completeCheck;?>"
onclick="compTask( '<?php echo $row['id'];?>' );">
and in js function deal with id from parameter:
function compTask(id) {
if (document.getElementById('complete-' + id).checked == true) {
document.getElementById('tr' + id).style.color = "green";
alert("hello");
}
}
Hy,
You need to add id in onclick="deleteTask('<?php echo $row['id']; ?>')">
Now in you function have id:
function deleteTask(id) { console.log(id) }
I have 3 different selectboxes. Second and third select boxes will be populated depending on first select boxes' value via ajax + php. But the response is not as i expected. It the shows error function. When i check it from the console there is no promlem with reading data from database as json format. But i'am unable to show these data as html to the screen. Here is my try:
HTML:
<table>
<tr>
<td valign="middle" align="center">
<label id="fieldOfBusinessLabel" for="fieldOfBusinessText">Field of Business</label>
</td>
<td valign="middle" align="center">
<select id="fieldOfBusinessSelectBox" class="selectBox" name="fieldOfBusinessSelectBox">
<option value="">--select--</option>
<?php
$result=mysqli_query($db,'SELECT * FROM field_of_business');
while($row=mysqli_fetch_assoc($result)) {
echo '<option value="'.$row["FobID"].'">'.$row['FobName'].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td valign="middle" align="center">
<label id="typeOfProductionLabel" for="typeOfProductionText">Type of Production/Service</label>
</td>
<td valign="middle" align="center">
<select id="typeOfProductionSelectBox" clas="selectBox" name="typeOfProductionSelectBox">
<option value="">--select--</option>
</select>
</td>
</tr>
<tr>
<td valign="middle" align="center">
<label id="mainProductsLabel" for="mainProductsText">Main Products/Services</label>
</td>
<td valign="middle" align="center">
<select id="mainProductSelectBox" clas="selectBox" name="mainProductSelectBox">
<option value="">--select--</option>
</select>
</td>
</tr>
</table>
JS:
$(document).ready(function(){
$("#fieldOfBusinessSelectBox").change(function(){
var value = $("select#fieldOfBusinessSelectBox option:selected").val();
$.ajax({
type: 'POST',
url: 'listData.php',
dataType: "json",
data:{fobID:value},
success:function(answer){
var data1 = "<option>--select--</option>";
var data2 = "<option>--select--</option>";
$.each(answer, function(i, answer){
data1 += "<option>"+answer.TopsName+"</option>";
});
$.each(answer, function(i, answer){
data2 += "<option>"+answer.MpsName+"</option>";
});
$('#typeOfProductionSelectBox').html(data1);
$('#mainProductSelectBox').html(data2);
},
error:function(){
alert("An error has occured !");
}
});
});
});
PHP:
<?php
include './config.php';
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'){
die('Wrong request !');
}
$fobID = mysqli_real_escape_string($db,$_POST['fobID']);
if(isset($_POST['fobID'])){
$stmt1 = $db->prepare("SELECT TopsName FROM type_of_production_service WHERE FobID = ?");
if($stmt1 == "false"){
die('Query error !'.$db->error);
}
$stmt1->bind_param('i', $fobID);
$stmt1->execute();
$result = $stmt1 -> get_result();
$topsName = $result ->fetch_all(MYSQLI_BOTH);
echo json_encode($topsName);
$stmt2 = $db->prepare("SELECT MpsName FROM main_products_services WHERE FobID = ?");
if($stmt2 == "false"){
die('Query error !'.$db->error);
}
$stmt2->bind_param('i', $fobID);
$stmt2->execute();
$result2 = $stmt2 -> get_result();
$mpsName = $result2 ->fetch_all(MYSQLI_BOTH);
echo json_encode($mpsName);
}
$db->close();
You have 2 json_encoded strings in result and it not decoded. User one json object:
PHP:
echo json_encode(array('mps' => $mpsName, 'tops' => $topsName));
JS:
answer = $.parseJSON(answer);
$.each(answer.tops, function(k,v){...});
$.each(answer.mps, function(k,v){...});