Reputation: 12335
I have a series of Delete icons displays as such:
echo '<img id="'.$items['id'].'" src="images/delete.png" />';
Where $items['id']
is a reference to the id of the DB item I would like that icon to delete.
How can I access this id in jquery when the item is clicked so I can then call a:
$.get('ajax/delete.php', { id: $('#id').val() },
function(data) {}
Or something of the sort.
Upvotes: 0
Views: 3451
Reputation:
I'd personally go for hijax and graceful degradation by wrapping the <img>s with <a>. Plus you most likely shouldn't do any delete/remove operations with GET. But here you go;
$('img[src=images/delete.png]').click(function(e) {
$.get('ajax/delete.php', { id: this.id }, function() {
// complete, perhaps get rid of the <img> now?
});
return false;
});
Upvotes: 0
Reputation: 532435
I would handle this slightly differently. I would have each delete icon followed by a hidden input that contains the value of the item corresponding to the id of the item to be deleted. I would then use jQuery to extract the value attribute of the hidden field. This way, you won't have to do any magic string manipulation to use numeric ids.
Also, never use a get request to do a delete. All some one has to do is type a URL in the proper format, with the proper credentials to bypass any client-side processing you've added to validate your deletion. AJAX allows you to send other types of requests and you should prefer a POST or DELETE request for deletes.
echo '<img class="deleteIcon" src="images/delete.png" />';
echo '<input type="hidden" value="' + $item[id] + '" />';
$('.deleteIcon').click( function() {
var id = $(this).next('input[type=hidden]').attr('value');
$.ajax({
url: 'ajax/delete.php',
type: 'delete',
data: { id: id },
dataType: 'json', // get back status of request in JSON
success: function(data) {
if (data.status) {
// remove row, or whatever
}
else {
// handle deletion error
},
... other parameters/callbacks ...
});
});
Upvotes: 0
Reputation: 95880
The following code will help you out. Add the class "delete" to each of your img.
$('.delete').onclick(function() {
var id = $(this).attr('id');
$.post('ajax/delete.php', { id: id } function(data) {
...
});
});
Upvotes: 5
Reputation: 187020
$("#imageID").click ( function () {
alert ( $(this).attr ( "id" ) );
});
if you have a class name
$(".yourclassname").click ( function () {
alert ( $(this).attr ( "id" ) );
});
Upvotes: 0