php variable value in a while loop for each row - php

I have a cancel button on each row of a table that is autopopulated in a while loop.
The $id resolves correctly but when I click on the cancel button all the active rows are modified. I only want the row that is concerned to be modified.
So in a while loop in php:
<tr id="dataTable">
<td id="nom"><?php echo $nom;?></td>
<td id="statut"><?php echo $statut;?> </td>
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" href="#" title="Annuler"
onclick="document.write('<?php
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$id."'";
$resultatannuler = $connexion->query($queryannuler); ?>'); location.reload(); 'return false';">Annuler</a>
</td>
</tr>
My problem is the 'statut' column is being updated for all the rows and not just the row where I click on the cancel button. Thanks if you can help.
UPDATE
I have tried to implement your different advices by using ajax. It's tough. I didn't specify in the original post that I am using a Wordpress framework. So I have modified #ssurli code to take into account wordpress
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" class="button delete" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
</td>
<script>
function cancelRecord(id) {
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {id:id},
action: 'delete_rdv',
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
console.log('The function is hooked up');
location.reload();
console.log('The function is hooked up2');
}
});
}
AND in my functions.php file
add_action( 'wp_ajax_delete_rdv', 'delete_rdv' );
add_action( 'wp_ajax_nopriv_delete_rdv', 'delete_rdv' );
function delete_rdv() {
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
}
I'm stuck on the very first hurdle.
The console is sending an error message :
admin.php?page=plugin-voc:1 Uncaught ReferenceError: cancelRecord is not defined
But my cancelRecord function is right after my button call so I don't understand this error.

Here the working code.
Update your table row as below:
<tr id="dataTable">
<td id="nom"><?php echo $nom;?></td>
<td id="statut"><?php echo $statut;?> </td>
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
</td>
</tr>
Add below js scripts to bottom of your html page. Include jquery cdn file only if not add to page already.
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
function cancelRecord(id) {
$.ajax({
type: 'post',
url: 'cancel.php', //use actual directory path, if not kept in root directory
data: {id:id},
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
location.reload();
}
});
}
</script>
Add PHP file having PHP code having DB query responsible for cancelling the record.
//cancel.php
<?php
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
Hope it will work for you. Feel free if you have any further query.

This was the original html request
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" class="button delete" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
The javascript function was not defined when I put it in the same file as the php. I moved into the plugin index.js file and most importantly I moved this line:
action: 'delete_rdv',
into data {}
data: {
action: 'delete_rdv',
id:id},
Here is the complete javascript code:
jQuery( document ).ready(function($){ $('.button.delete').on('click', function(){ let id = $(this).attr('id'); cancelRecord(id); }); });
function cancelRecord(id) {
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {
action: 'delete_rdv',
id:id},
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
location.reload();
}
});
}
The ajax calls the function delete_rdv which I put in the functions.php file
add_action( 'wp_ajax_delete_rdv', 'delete_rdv' );
add_action( 'wp_ajax_nopriv_delete_rdv', 'delete_rdv' );
function delete_rdv() {
$queryannuler = "UPDATE wp_RDV SET statut = 'Annulé' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
}
Special thanks to #jeprubio for kinda forcing to look the ajax way and to #sssurii for posting his code and answering my question.

Related

Delete Task on a todo list, without refreshing the site with PHP

I am working an a to-do list with php and mysql. I have already connected my programm with the Database. Now I have this output:
2022-09-24 X Task1
2022-09-24 X Task2
2022-09-24 X Task1
the HTML looks
<ul>
<li><span>X </span>Task1</li>
<li><span>X </span>Task2</li>
<li><span>X </span>Task3</li>
</ul>
How i can delete a Task with php, if I click on "X" without refreshing the site?
your HTML should like (don't forget to save the file as PHP):
<tr class="delete_task<?php echo $id ?>">
<td><?php echo $row_task['task_name']; ?></td>
<td>
<a class="btn btn-success" id="<?php echo $id; ?>">Delete</a>
</td>
</tr>
you need to add event on button with js code first
<script type="text/javascript">
$(document).ready(function() {
$('.btn-success').click(function() {
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this Member?")) {
$.ajax({
type: "POST",
url: "task_delete.php",
data: ({
id: id
}),
cache: false,
success: function(html) {
$(".delete_task" + id).fadeOut('slow');
}
});
} else {
return false;
}
});
});
</script>
your PHP code in task_delete.php
<?php
include ('database.php'); // your DB connection
$id = $_GET['id'];
$delete_data"delete from tasks where task_id = '$id' ";
$database->exec($delete_data);
?>

Delete function using AJAX in CodeIgniter

PROBLEM SOLVED.. I update my code accordingly.. Thanks all
Intro: My code display array of message traces (each message display in grey-panel). User can delete unwanted message by click on delete button, the message will be deleted in both DB and disappear from screen.
Seems my delete function is not working.. Appreciate for advice.. I don't know AJAX.. this is my first try. Thanks in advance.
The following are my code:
ajax code:
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var $btn = $(this),
$li = $btn.closest('li');
var traceId = $li.data('trace-id');
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
data: { 'traceId': traceId },
success: function (res) {
if (res === '1') {
$btn.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
part of view code:
<ul id="responds">
<?php foreach ($line as $dataName => $contents){ ?>
<li data-trace-id="<?php echo $contents->trace_id; ?>">
<div class="grey-panel" style="text-align:right">
<div class="del_wrapper" id="<?php echo $contents->trace_id; ?>">
<a href="#" class="del_button" id="<?php echo $contents->trace_id; ?>" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id; ?>" >
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php print $contents->trace_hdr.'<br />';
print $contents->trace_src.'<br />';
print $contents->trace_dest.'<br />';
// some other things ?>
</div>
</div>
</li>
<?php } ?>
</ul>
controller code:
public function traceDelete($traceID) {
if ($traceId = $this->input->post('traceId')) {
return $this->model_general->deleteTrace($traceId);
}
return false;
}
model code:
public function deleteTrace($id) {
$this->db->where('trace_id', $id);
$this->db->delete('trace_tbl');
return $this->db->affected_rows() > 1 ? true:false;
}
First, you are using the id attributes wrong. They are meant to be unique as in appear on one element and not multiple as you have done. (As well, id attributes cannot start with a digit.) There's really no need to put it on multiple containing elements as you can easily traverse to the parents or children with jQuery's .find(), .parent(), .closest(), and other traversing methods. However, this should not be the cause of your problem.
Now, what I do think is the cause of your problem is that you are passing the 2nd character of your id attribute into your AJAX request.
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
// assign the ID e.g. "abc" to clickedID
var clickedID = this.id;
// problem: assign the second character of your ID i.e. "b" into DbNumberID
var DbNumberID = clickedID[1];
// assign the same value to myData (which is redundant)
var myData = DbNumberID;
$(this).hide();
jQuery.ajax({
type: "POST",
url: 'traceDelete',
dataType:"text",
// sending "myData=b"
data: { myData: myData },
success:function(traceDelete){
alert("Deleted");
$(DbNumberID).fadeOut();
},
error:function(xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
I am not too familiar with CodeIgniter anymore, but you need to get value from the $_REQUEST or $_POST array or use their built-in function.
$myData = $this->input->post('myData'); // because you are sending myData
EDIT
This is untested but here's how I would do it.
HTML
First, let's use HTML5 data attribute call it data-trace-id. This will be used instead of your numerous improper usages of id attributes.
<ul id="responds">
<?php foreach ($line as $dataName => $contents) : ?>
<li data-trace-id="<?php echo $contents->trace_id ?>">
<div class="grey-panel" style="text-align: right">
<div class="del_wrapper">
<a href="#" class="del_button" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id ?>">
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php echo $contents->trace_hdr ?><br />
<?php echo $contents->trace_src ?><br />
<?php echo $contents->trace_dest ?><br />
<!-- etc -->
</div>
</div>
</li>
<?php endforeach ?>
</ul>
JavaScript
Next, let's simplify your JavaScript. I'll use the dreaded alert() for debugging purposes -- but it's usually better to use console.log().
$(function() {
$("#responds").on("click", ".del_button", function (e) {
e.preventDefault();
// keyword 'this' refers to the button that you clicked;
// $(this) make a jQuery object out of the button;
// always good idea to cache elements that you will re-using;
var $li = $(this).closest('li');
// get the associated trace ID from the list-item element;
var traceId = $li.data('trace-id');
alert('trace ID ' + traceId);
// assuming you only want to hide the message only if it has been been successfully deleted from the DB?
// if that is the case, then you have to wait for the AJAX response to tell you whether it was
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
// notice how I am using 'traceId'? on the server-side, the data will accessible by using $_POST['traceId'] or $this->input->post('traceId')
data: { 'traceId': traceId },
// look at the response sent to you;
// if I am not mistaken (boolean) true and false get sent back as (strings) 1 or 0, respectively;
// so if the response is 1, then it was successfully deleted
success: function (res) {
alert('AJAX response ' + res);
if (res === '1') {
alert('hiding button');
// hide the message
$li.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
PHP
Lastly, we take the value from the $_POST array. Check whether there is a value: if so, delete the item; otherwise ignore it.
public function traceDelete()
{
if ($traceId = $this->input->post('traceId')) {
echo $this->model_general->deleteTrace($traceId) ? '1' : '0';
}
echo '0';
}
remove var DbNumberID = clickedID[1]; var myData = DbNumberID;, as its not needed. Directly assign data: { myData: clickedID },. Also get value of myData in controller via POST.
public function traceDelete() {
$traceID = $this->input->post('myData');
if($traceID)
return $this->model_general->deleteTrace($traceID);
return false;
}

How to delete row form ajax when it is deleted

hello i am trying to delete a row with check box delete when i delete any record it is deleting from database and i can see with refreshing page.
I want to delete the row without refresh how can i achieve that:
This is my listing code:
<tbody>
<?php while($staffResults=$staffQuery->fetch_assoc()){ ?>
<tr>
<td><input type="checkbox" class="staff-list" name="checked" value="<?php echo $staffResults['id_staff']; ?>"></td>
<td><?php echo $staffResults['staff_name']; ?></td>
<td><?php echo $staffResults['staff_email']; ?></td>
<td><?php echo $staffResults['staff_phone']; ?></td>
<td><?php $datetime = $staffResults['staff_registered'];
echo date("d-m-Y", strtotime($datetime)); ?></td>
</tr>
<?php } ?>
</tbody>
And delete button:
<button type="button" id="deleteStaffList" class="btn btn-sm btn-default" title="Remove"><i class="fa fa-trash-o"></i></button>
Here is my script and ajax code.
<script language="JavaScript">
$("#deleteStaffList").click(function()
{
$("#delshowMessageDiv").hide();
$("#delshowMessage").html('');
var deleteStaffList = $('.staff-list:checkbox:checked').map(function(){
return $(this).attr('value');
}).get().join(",");
console.log(deleteStaffList);
$.ajax({
url: "staffcontroller.php",
method: "POST",
data: { delData : deleteStaffList, 'action':'delete'},
dataType: "json",
success: function (response) {
if(response["success"]==true)
{
$("#delshowMessageDiv").hide();
$("#delshowSuccessMessageDiv").show();
$("#delshowSuccessMessage").html(response["message"]);
}else{
$("#delshowMessageDiv").show();
$("#delshowMessage").html(response["message"]);
}
},
error: function (request, status, error) {
$("#delshowMessageDiv").show();
$("#delshowMessage").html("OOPS! Something Went Wrong Please Try After Sometime!");
}
});
return false;
});
</script>
You can place 3 lines as follows: (// new lines -there comment- // till here)
<script language="JavaScript">
$("#deleteStaffList").click(function()
{
$("#delshowMessageDiv").hide();
$("#delshowMessage").html('');
var deleteStaffList = $('.staff-list:checkbox:checked').map(function(){
return $(this).attr('value');
}).get().join(",");
console.log(deleteStaffList);
$.ajax({
url: "staffcontroller.php",
method: "POST",
data: { delData : deleteStaffList, 'action':'delete'},
dataType: "json",
success: function (response) {
if(response["success"]==true)
{
$("#delshowMessageDiv").hide();
$("#delshowSuccessMessageDiv").show();
$("#delshowSuccessMessage").html(response["message"]);
}else{
$("#delshowMessageDiv").show();
$("#delshowMessage").html(response["message"]);
// new lines
$('.staff-list:checkbox:checked').each(function(i,e){
$(this).parents('tr').remove();
})
// till here
}
},
error: function (request, status, error) {
$("#delshowMessageDiv").show();
$("#delshowMessage").html("OOPS! Something Went Wrong Please Try After Sometime!");
}
});
return false;
});
</script>

Issue with AJAX "load more" button: disappears once clicked

EDIT: thanks everyone for your help. It still doesn't work though.
This script works fine if i change the table to an ordered list. (tr = ol and td = li) That's why i really think the issue comes from the append part of the code. Any ideas?
Everything seems to work fine except for the "load more" button that disappears after it's been clicked. The new posts load but the users cannot click on the button again to load more posts. I've looked on SO but couldn't find a fix for my issue.
If I remove this line:
$("#more"+ID).remove();
then the button does show up but the gif image keeps on loading forever and the button is not clickable...
Here's the index.php code:
<table id="update_list" >
<tbody>
<?php
$result=query("SELECT * FROM postlist ORDER BY postid DESC LIMIT 9");
foreach ($result as $row)
{
$postid=$row['postid'];
$post=$row['post'];
?>
<tr id="<?php echo $postid ?>">
<td>
<?php echo $post; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="more<?php echo $postid; ?>" class="morebox">
more
</div>
</div>
</body>
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="/loading.gif" />');
$.ajax({
type: "POST",
url: "loadmore.php",
data: "lastpost="+ ID,
cache: false,
success: function(html){
$("#update_list >tbody").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
</script>
</html>
Here is the loadmore php page:
<?php
include("includes/config.php");
if(isset($_POST['lastpost']))
{
$lastpost=$_POST['lastpost'];
$result=query("SELECT * from postlist WHERE postid < '$lastpost' ORDER BY postid DESC
LIMIT 5");
foreach ($result as $row){
$postid=$row['postid'];
$post=$row['post'];
?>
<tr id="<?php echo update$postid ?>">
<td>
<?php echo $post; ?>
</td>
</tr>
<?php } ?>
<div id="more<?php echo $postid; ?>" class="morebox">
more
</div>
<?php }?>
Any tips on what i'm doing wrong here ?
Thanks !
Try this:
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).find("a").hide().insertAfter('<img src="/loading.gif" />'); //hide a link and insert image after it
$.ajax({
type: "POST",
url: "loadmore.php",
data: "lastpost="+ ID,
cache: false,
success: function(html){
$("#update_list >tbody").append(html);
$("#more"+ID).find("img").remove(); // remove img
$("#more"+ID).find("a").show(); //and show link
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
You are removing the load more button after button clicked
$("#update_list >tbody").append(html);
//$("#more"+ID).remove(); remove this line

Deleting a list item <li> with jquery?

I'm trying to delete a li item using jquery, but its not working. Here's my code:
the html file:
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div>
$reply_info
<div class="date"></div>
<a class ="delbutton" href="#" id = $id> Delete </a>
</div>
<div class="clear"></div>
</li>
The jquery file:
$(function () {
$(".delbutton").click(function () {
var del_id = element.attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
the delete.php file:
<?php
include("includes/connect.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
There is no element in your HTML with a class of record. I would try something like this:
<li class="record">
<!-- a bunch of other stuff -->
<a class="delbutton" href="#">Delete</a>
</li>
then in the JS:
$(function ()
{
$(".delbutton").click(function ()
{
if (confirm("..."))
{
$.ajax({ /* ... */});
$(this).closest(".record").fadeOut();
}
return false;
});
});
If your div look like this:
<ul>
<li>One | <a href='#' class='delete'>Delete</a></li>
<li>Two | <a href='#' class='delete'>Delete</a></li>
<li>Three | <a href='#' class='delete'>Delete</a></li>
<li>Four | <a href='#' class='delete'>Delete</a></li>
</ul>
jQuery:
jQuery(document).ready(function(){
jQuery('.delete').live('click', function(event) {
$(this).parent().fadeOut()
});
});​
Check: http://jsfiddle.net/9ekyP/
EDIT:
You can remove your li after getting response in success function something like this:
jQuery(document).ready(function(){
jQuery('.delbutton').live('click', function(event) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
$(this).parent().parent().fadeOut();
}
});
});
});​
There are several issues with your code...
element.attr("id") references undeclared element but this should probably be $(this).attr("id")
The <li> block has no class ".record" either
EDIT: You only fade your <li> but do not actually remove it from the DOM (don't know if this was deliberate though)
The <a>'s ID is not quoted (and not escaped either... as are the other strings you insert in PHP (EDIT) and the ID you use in your delete script - this is very dangerous as it allows cross-site scripting / XSS and SQL injection as TokIk already pointed out)
PHP:
echo '<li class="record">
<img class="avatar" src="images/'.htmlentities($picture).'" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>'.htmlentities($username).'</strong> '.htmlentities($auto).'
<div class="date">'.htmlentities($rel).'</div>'.htmlentities($reply_info).'<div class="date"></div> <a class="delbutton" href="#" id="'.htmlentities($id).'"> Delete </a>
</div>
<div class="clear"></div>
</li>';
JavaScript:
$(document).ready(function() {
$(".delbutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
EDIT: Delete script (note the additional error check that $_POST['id'] exists and the pseudo-function for quoting the ID):
<?php
include("includes/connect.php");
if( isset($_POST['id']) ) {
$id = quote($_POST['id']);
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
I am assuming that '.records' is the container.
You can pass through your ID value to make <li> unique, result being:
<li id='record_12'>
//CONTENT
</li>
<li id='record_13'>
//CONTENT
</li>
And change your SUCCESS script to the following:
$(".delbutton").click(function(){
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
//Getting the unique LI and fading it out
$('#record_' + del_id).fadeOut();
}
});
Your code works fine well.I was trying to code a form that has multiple textbox, then after each textbox threre will be link called add which POST call the other php called addnew.php.
In addnew.php data will we added to database(postgres). But I am geting problem while getting the post variable itself.
this is my code for form (I will chage for multiple textbox once it works fine)
script:
<script type='text/javascript'>
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.add').live('click', function(event) {
var da = $('form#myform').serialize();
alert(da);
$.ajax({
type: "POST",
url: "addnew.php",
data:da,
success: function(data) {
if (data === "ok") {
$(this).parent().fadeOut();
$('#results').html(data);
}
else {
alert(data);
}
}
});
});
});
});
Form
<form name='myform' id='myform'>
<input name='da' type='text' id='da' value='none'>
<a href='#' class='add'>Add</a>
</form>
addnew.php code here
<? php
if( isset($_POST['da']) )
{
echo (da);
}
?>

Categories