user715564 user715564 - 5 months ago 31
Ajax Question

Using Ajax to delete a database row only deletes the first row, not the selected row

I'm using the code below to loop through my database rows and display the info. Each form has a delete button that should delete that row from the database :

function show_scheduled_tweets () {
global $wpdb;
$query = "SELECT * FROM wp_tweettweet";
$results = $wpdb->get_results($query, ARRAY_A);

foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
?>

<form id="tweet-<?php echo $id; ?>" class="tweetclass form-inline" action="" method="post">
<div class="checkbox">
<label>
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
</label>
</div>
<div class="form-group"><input class="form-control" type="text" name="tweet" value="<?php echo $tweet2; ?>"></div>
<div class="form-group"><input class="form-control" type="text" name="tweetdate"></div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="form-group"><input class="form-control" type="text" name="timepicker" class="timepicker"/></div>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
}
show_scheduled_tweets();


Here is my Ajax :

jQuery('.tweetdelete').click(function(event) {
event.preventDefault();
var id = jQuery('input[name="id"]').val();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
'action': 'db_tables_delete',
'id': id
},
beforeSend: function() {
alert('before')
},
success: function(){
alert('success')
},
error: function(){
alert('error')
},
});
});


Let's say I have five different rows of data showing. Now matter which delete button I click, the top row will always be deleted. In other words, if I click the delete button for row 3, the first row will be deleted.

Answer

As per your current code val() returns value of first element. Check the description from documentation :

Get the current value of the first element in the set of matched elements or set the value of every matched element.


You need to get the id value based on clicked element, use prevAll()

var id = jQuery(this).prevAll('input[name="id"]').val();


or siblings() method

var id = jQuery(this).siblings('input[name="id"]').val();


or with closest()(or parent()) and find()

var id = jQuery(this).closest('form').find('input[name="id"]').val();