Reputation: 1690
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.
Upvotes: 0
Views: 554
Reputation: 824
Your selector for the US is not particular to the tweet in the firm. The event passed to the JS function will carry with it a target (which will be the button that was clicked), if you echo your $id into a data attribute of that button then the relevant id it will be accessible within the target:
<input data-id="<?php echo $id;?>" class="tweetdelete" type="submit" value="delete">
and in your JS:
var id = jQuery(event.target).attr('data-id');
Upvotes: 0
Reputation: 115232
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();
siblings()
method
var id = jQuery(this).siblings('input[name="id"]').val();
closest()
(or parent()
) and find()
var id = jQuery(this).closest('form').find('input[name="id"]').val();
Upvotes: 3