I have a html table populated with mysql data. Each row has an id (e.g 001, 002 etc). Within each table row I have created a button. I'd like to be able to post the current time in milliseconds (working fine) as well as the relevant id of the row (which the button clicked is in) to an Ajax file. My Ajax file works fine I just can't get the right id to post.
I have tried using <?php echo $row=$REQUEST ['id']?> but it only returns the first value in the table not the respective one.
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID Number</strong></th>
<th><strong>Class</strong></th>
<th><strong>Crew</strong></th>
<th><strong>Start</strong></th>
<th><strong>Finish</strong></th>
</tr>
</thead>
<tr>
<td align="center"><?php echo $row["number"];?></td>
<td align="center"><?php echo $row["class"];?></td>
<td align="center"><?php echo $row["crew"]?></td>
<td> <input type="hidden" id="boatnumber" name="custId" value="<?php echo $row["number"];?>"<button id="startbutton" type="submit" class="newbutton"></td></tr>
<script>
$(document).ready(function() {
var delay = 2000;
$('.newbutton').click(function(e){
e.preventDefault();
var d = new Date();
var start = d.getTime()
var id = $('#id').val();
if(start == ''){
$('.message_box').html(
'<span style="color:red;">Enter Your Username!</span>');
$('#start').focus();
return false;
}
var boatnumber = $('#boatnumber').val();
if(boatnumber == ''){
$('.message_box').html('<span style="color:red;">Enter Your Boat
ID!`</span>');
$('#boatnumber').focus();
return false;
}
$.ajax({
type: "POST",
url: "ajax/start.php",
data: "start="+start+"&boatnumber="+boatnumber,
beforeSend: function() {
$('.message_box').html(
'<img src="Loader.gif" width="25" height="25"/>');},
success: function(data){
setTimeout(function() {
$('.message_box').html(data);}, delay);
}
});
});
});
</script>
It only sends the id of the first row in the table not the id of the row where the button (that is clicked) is.
You are getting the value of an element with the ID of #boatnumber, you can't have multiple elements with the same ID.
A better way maybe to use a data attribute on the button that holds the number and then retreive it in your script.
HTML:
<button type="submit" class="newbutton" data-number="<?php echo $row['number'] ?>">
Script:
var boatnumber = $(this).data('number);
Related
I have a table that it's content is comes from database.When I click on the delete button I want to delete that row with Ajax. Actually right now it's working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .
$('.dashboard-subscribe-form').submit(() => {
event.preventDefault();
const currentHiddBtn = $('.dash-subscribe-form-btn');
console.log(currentHiddBtn.closest('tr'));
const userCaution = confirm('Want to delete this quote?');
if (userCaution) { //If admin insists to delete the row
const deleteId = $('.dash-subscribe-form-btn').attr('value');
$.ajax({
type: "POST",
url: "delete-subscribe.php",
dataType: "json",
data: {
deleteId: deleteId
},
success: (data) => {
if (data.code === '200') {
console.log('It works!');
currentHiddBtn.closest('tr').css('background', 'tomato');
currentHiddBtn.closest('tr').fadeOut(1200, () => {
});
} else if (data.code === '404') {
alert('An error occurred!Please try again.');
}
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tbody>
<?php
$count = 1;
$sqlCommand = "SELECT * FROM `kq0b3_subscribe`";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$sqlCommandPrepare->execute();
while ($result = $sqlCommandPrepare->fetch()) {
?>
<tr id="row-<?php echo $result['id']; ?>">
<td class="dashboard-records">
<?php echo $count; ?>
</td>
<td class="dashboard-records">
<?php echo $result['email']; ?>
</td>
<td>
<form action="" method="post" class="dashboard-subscribe-form">
<input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/>
<button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete
</button>
</form>
</td>
</tr>
<?php
$count++;
}
?>
</tbody>
delete-subscribe.php:
<?php
require_once('config.php');
$delete_row = $_POST['deleteId'];
if($delete_row){
$sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$result = $sqlCommandPrepare->execute([
$delete_row
]);
/*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
last line of code) */
echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}
UPDATE2: now I'm using :
$('#row-' + deleteId).css('background', 'tomato');
$('#row-' + deleteId).fadeOut(1200, () => {
});
but the new problem is : it doesn't matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?
I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.
The code causing this is:
const deleteId = $('.dash-subscribe-form-btn').attr('value');
You want to be getting the target input from the event object passed from your .submit().
I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.
$('.dashboard-subscribe-form').submit((event) => {
event.preventDefault()
console.log(event.target.elements[0]["value"])
$('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})
It is selecting the first element within the elements array which is the input. If you want the button you can use event.target.elements[1]
You could then also use the value returned to remove the <tr> with the same id instead of finding the nearest. This could be done in the success part of your ajax call without doing a refresh.
Some strange problem occurred. I am trying to delete a record from a table by using AJAX but whenever I click the delete button it is sending the ID of the last row in the table each time instead of that specific ID which I want to delete to my delete-process.php page. Now I checked that the PHP page and codes are just working fine. When I did console.log(dataString) I got to see that no matter which Delete button I click I get the ID of the last field only.
Code
<table class="table table-hover table-striped">
<thead>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Date</th>
<th>Action</th>
</thead>
<tbody>
<?php while($si = $stmt->fetch()){ extract($si); ?>
<tr>
<td><?php echo $ct_id; ?></td>
<td><?php echo $ct_name; ?></td>
<td><?php echo $ct_email; ?></td>
<td><?php echo $ct_phone; ?></td>
<td><?php echo date('jS M, Y (h:i a)', strtotime($ct_date)); ?></td>
<td>
<form method="post" action="">
View
<input type="text" value="<?php echo $ct_id; ?>" class="ctid">
<input type="submit" value="Delete" class="btn btn-danger btn-fill delete">
</form>
</td>
</tr>
<?php } ?>
</tbody>
AJAX
$(document).ready(function() {
$(".delete").click(function() {
var dataString = {
id: $(".ctid").val()
};
console.log(dataString);
var $submit = $(this).parent().find('.delete');
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to delete this message?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
//dataType : "json",
url: "delete-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$submit.val("Please wait...");
},
success: function(html){
$('.message').html(html);
if($('.message').find('#responseBox').hasClass('alert-success')){
$.alert(html);
setTimeout(function(){
window.location.replace("support.php<?php if(!empty($_GET['ids'])){ ?>?ids=<?php echo $_GET['ids']; } ?>");
},2000);
}
}
});
},
cancel: function(){}
}
});
return false;
});
});
I did not include PHP code because the error is detected in console.log(dataString) as every button clicked is sending the same ID. Please help.
$(".ctid") will return an array containing all of the elements with that class.
You are only interested in the sibling to the clicked button so you should use $(this).prev().
$(this) will reference the clicked button.
.prev() selects the immediately proceeding sibling.
$(".delete").click(function() {
var dataString = {
id: $(this).prev().val()
};
...
});
As you are creating the table rows using loop so the class ctid is repeated. so when you are accessing this like this id: $(".ctid").val(). It will return all the elements having class ctid. So change your script like this
var dataString = {
id: $(this).siblings('.ctid').val()
};
Of course it is selecting the same ctid since you don't distinguish between forms. You can distinguish like this:
var dataString = {
id: $(this).closest('form').find('.ctid').val()
};
"closest" navigates to the form and then find the ctid that is contained in the form.
When you do this:
$(".ctid").val()
Which matching element are you expecting? The code doesn't specify, and ".ctid" matches multiple elements. But since it can only return a single value, it's simply returning the last matching one. Essentially, you need to specify which matching element you want.
One way to do this is by navigating the DOM from the clicked button to the nearest matching element. Perhaps by navigating up to a single common parent element and then finding the target element therein. Something like this:
$(this).closest("form").find(".ctid").val()
Starting from the clicked element which raised the event (this), it navigates up to the containing <form> and then searches for the matching ".ctid" within that form. Then gets the value from only that element.
You can inspect to check each button value is getting unique or not
You can achieve that without using ajax use below code
Delete
I'm facing major issue in changing status of a particular row in table with <select> tag .
I'm using jquery-Ajax so, here go functionality by this when is click on <select on any particular row for Example: Lets say i have changed the status of table row of id 2 from Pending to Delivered. On this jquery change() event triggers and it fetchs the value from 'tag' and sends the value to other file through ajax. Till here everything goes right the data goes through ajax and row with particular id's status is getting updated successfully.
But on Front end it does not change the status of the particular row. but it changes status of only first row .
Here i need it to change status of the particular row.
Note : I have searched in stackoverflow for this question. but those answere not come close to my question. Here are those links below Link 1link2link3
THANK YOU IN ADVANCE
Here is the Output and i have explained details in images also
There is the full code
HTML page : index.php
<?php
include('processing.php');
$newobj = new processing();
?>
<html>
<head>
<title>Jquery Ajax select <tag> with PHP Mysql</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table border="1">
<tr>
<th>Id</th>
<th>Product name</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php echo $newobj->display();?>
</table>
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
$("#display").html(result);
}
});
});
});
</script>
</body>
</html>
AJAX HANDLER PAGE : ajaxreceiver.php
<?php
include('processing.php');
$newobj = new processing();
if(isset($_POST['statusname'],$_POST['getid'])){
$statusid = $_POST['statusname'];
$id = $_POST['getid'];
$newobj->getdata($statusid,$id);
}
?>
PHP CLASSES FILE : processing.php
<?php
class processing{
private $link;
function __construct(){
$this->link= new mysqli('localhost','root','','example');
if(mysqli_connect_errno()){
die ("connection failed".mysqli_connect_errno());
}
}
function display(){
$sql = $this->link->stmt_init();
$id=1;
if($sql->prepare("SELECT id,productname,status FROM ajaxselect")){
$sql->bind_result($id,$productname,$status);
if($sql->execute()){
while($sql->fetch()){
?>
<tr>
<td><?php echo $id;?></td>
<td><?php echo $productname;?></td>
<td><p id="display"><?php echo $status;?></p></td>
<td>
<select status-id=<?php echo $id;?> id="selectstatus" class="selectstatus">
<option>Pending</option>
<option>Delivered</option>
<option>Cancelled</option>
<option>Amount Paid</option>
</select>
</td>
</tr>
<?php
}
}
}
}
function getdata($statusid,$id){
$sql = $this->link->stmt_init();
if($sql->prepare("UPDATE ajaxselect SET status=? WHERE id=?")){
$sql->bind_param('si',$statusid,$id);
if($sql->execute()){
echo $statusid;
}
else
{
echo "Update Failed";
}
}
}
}
?>
the problem is in this line :
$("#display").html(result);
so what's going here ?
you are creating display id for every row, which is not good practice to do , specially in your particular .
there are various solutions for this problem ,
1)
("#display", $(this).parent().parent()).html(result);
here you are going to apply the action to particular ID which is belongs to the parent of the parent of the particular class which had received the change action
2)
giving the display row unique id for each row
for example like follows :-
<td><p id="display_<?php echo $id; ?>"><?php echo $status;?></p></td>
and then apply your action to it directly ,
$("#display_" + getid).html(result);
3)
and this solution is similar to the past one , by giving the parent <tr> a unique id
for example :-
<tr id='parent_<?php echo $id; ?>'>
and then apply your action it from your ajax like this
$("#display", $('#parent_' + getid)).html(result);
or even :
$('#parent_' + getid + ' #display').html(result);
Yes there is problem in $("#display").html(result); line because id ($("#display")) always select first element found in the DOM you can fix it by - following code-
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
// make jquery object that make reference to select in which click event is clicked
$this = $(this);
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
// this refer to the ajax callback function so we have to use $this which is initialized before ajax call
$($this).parents('tr').find("#display").html(result);
}
});
});
});
</script>
I need to update a row of a table. So when I click on a cell, I want it to be transformed into text box, so I used this:
<td contenteditable></td>
And then, when the content of a <td> is changed, I need to send it through AJAX to update it in the server without clicking on a button, so it will use the .change(function()).
I tried to get the content changed into a variable:
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = '<?php echo $row['id'] ?>';
var name = $("#emp_name").val();
var position = $("#position").val();
var salary = $("#salary").val();
$.ajax
({
url: 'update.php',
type: 'POST',
data: {dataId: rowid, data1: name, data2: position, data3: salary},//Now we can use $_POST[data1];
dataType: "text",
success:function(data)
{
if(data=="success")
{
//alert("Data added");
$("#before_tr").before("<tr><td>"+emp+"</td><td>"+pos+"</td><td>"+sal+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
}
},
error:function(data)
{
if(data!="success")
{
alert("data not added");
}
}
});
});
The problem is how to know which row is changed to send it via AJAX ? I am not getting any errors even when data not updated.
Here is the update.php code:
try
{
$rowid = $_POST['dataId'];
$emp_name = $_POST['data1'];
$pos = $_POST['data2'];
$sal = $_POST['data3'];
$upd = "UPDATE emp SET name = :emp_name, position = :pos, sal = :sal WHERE id = :rowid";
$updStmt = $conn->prepare($upd);
$updStmt->bindValue(":rowid", $rowid);
$updStmt->bindValue(":emp_name", $emp_name);
$updStmt->bindValue(":pos", $pos);
$updStmt->bindValue(":sal", $sal);
$updStmt->execute();
echo "success";
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
HTML:
<tbody>
<?php
$sql = "SELECT * FROM employee";
$stmt=$conn->prepare($sql);
$stmt->execute();
$res=$stmt->fetchAll();
foreach($res as $row){
?>
<tr id=""<?php echo $row['id'] ?>"">
<td contenteditable><?php echo $row['emp_name'] ?></td>
<td contenteditable><?php echo $row['position'] ?></td>
<td contenteditable><?php echo $row['salary'] ?></td>
</tr>
<?php } ?>
When loading your data with PHP you need to keep the row id in your html:
<tr id="<?php echo $yourList["id"]; ?>">
<td contenteditable></td>
</tr>
Then in your javascript you can catch it using the parent() jquery function
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid =$(this).parent().attr("id");
......
UPDATE
Check this example, I have added listeners to detect contenteditable td changes, I think you shall add it too , refer to this contenteditable change events for defining proper change events on contenteditable fields.
Explanation:
The contenteditable does not trigger change events, this work around is used to detect the focus event of the td using jquery on method and event delegation. The original content is saved in the td jquery data object $this.data('before', $this.html()); . Then when the user leaves the field or triggers any of the events 'blur keyup paste input', the current content is compared to the content in the data object, if it differs, the change event of the td is triggered.
$(document).ready(function(){
$('table').on('focus', '[contenteditable]', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).on('blur keyup paste input', '[contenteditable]', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = $(this).parent().attr("id");
$("#res").html(rowid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="500px">
<tr id="1222">
<td contenteditable></td>
</tr>
<tr id="55555">
<td contenteditable></td>
</tr>
</table>
Row Id : <span id="res"></span>
<tr row_id="<?php echo $row['id'] ?>"> ></tr>
In Your Ajax
var rowid = $(this).attr('row_id');
My script’s AJAX calls the following PHP file and prints a table with $attrib and text boxes.
Can somebody tell me how to collect the $attrib and text box in an array or something like that?
Code tried is giving values like "assetattrib%5B%5D=model". So please help me to correct this or show me a new way to do the same.
echo "<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id=addattrib >";
while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib'];
echo "<tr bgcolor='white'>
<td class='value'>$attrib</td>
<td class='value'><input type=text name=assetattrib[] value = '' </td>
</tr>";
}
echo "</table>";
echo "<input type=submit name='btnSaveAsset' id = 'btnSaveAsset' value='Save' >";
I tried the code below.
$(document).on("click", "#btnSaveAsset", function() {
$(document.getElementsByName('assetattrib[]')).each(function() {
var x = $(this).serialize();
alert(x);
});
});
IMPORTANT:
PHP mysql_ extension is deprecated and using it represents a major security issue. According to php.net
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used.
Now the actual answer:
I suggest some changes in your HTML, if you can make them:
Wrap the table where the <input>s are into a <form> element
Give the generated <input>s the name attribute given by $attrib, for example <input name="user" />
If you cannot modify the PHP/HTML code let me know and we'll find a workaround
I updated your jsfiddle using this changes. Your PHP code should end up like this:
<form id="btnSaveAsset" onsubmit="return false;">
<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id='addattrib'>
<?php while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib']; ?>
<tr bgcolor='white'>
<td class='value'><?php echo $attrib; ?></td>
<td class='value'><input type='text' name='<?php echo $attrib; ?>' /> </td>
</tr>
<?php } ?>
</table>
<input type=submit name='btnSaveAsset' id='btnSaveAsset' value='Save' />
</form>
Then, you collect your data with one of this options:
$(document).on("click", "#btnSaveAsset", function () {
var data = $("#myForm").serializeArray();
console.log(data); // Array of objects
});
OR
$(document).on("click", "#btnSaveAsset2", function () {
var tempData = $("#myForm").serializeArray();
var data = {};
$.each(tempData, function () {
data[this.name] = this.value;
});
console.log(data); // Just an object
});
Here is the jsfiddle updated: http://jsfiddle.net/jormaechea/sy0wx8gb/1/
Check your JS console (Press F12 and go to Console tab) to see the results.