Reputation: 7519
I am using this photo gallery from Codrops to display the images. I've added a button to delete the current image which is clicked [and enlarged]. However this doesn't delete the image which is clicked, but it deletes the first photo in the album.
How do I get the image path of the image which is clicked [i.e. current image]?
This is the jQuery code that I've added to the gallery script:
var image = $('#photos').attr("alt");
/* If delete is called */
$('#adelete').click(function(){
//create post data
var postData = {
"image" : image
};
//make the call
$.ajax({
type: "POST",
url: "delete.php",
data: postData,
success: function(data){
alert("Image deleted successfully! " +image+data);
}
});
});
PHP:
<?php
$image = $_REQUEST['image'];
if (isset($image)) {
unlink($image);
echo "Success";
}
?>
'photos' is the ID of the image.
echo "<img id='photos' src='/thumbs/$image' alt='$dirname/$image' />";
If I use var image = $('#wrapper img').attr("alt");
as in the gallery code, it gives an undefined
error and no images are deleted. I'm assuming this is because the enlarged image is loaded at runtime.
Upvotes: 1
Views: 3714
Reputation: 532695
The problem is that the image that you are putting on the page isn't the same image element that is loaded in the panel. You should search for the matching image in your content area that has the same url as the image in the panel that you want to delete, then get it's alt
attribute. [Do you really need alt
or couldn't you figure out from the src
what the directory is on the server? If so, that would save you from having to do the second look up; you could just pass back the url from the panel image.]
/* If delete is called */
$('#adelete').click(function(){
var src = $('#wrapper img').attr('src');
var image = $('#content img:has([src="' + src + '"])').attr('alt');
//create post data
var postData = {
"image" : image
};
//make the call
$.ajax({
type: "POST",
url: "delete.php",
data: postData,
success: function(data){
alert("Image deleted successfully! " +image+data);
}
});
});
Upvotes: 1
Reputation: 32537
You need to put var image = $('#photos').attr("alt");
inside your .click(...)
Upvotes: 0
Reputation: 27451
I don't know about all that other mess, but to get the path of an image that was clicked just do this:
$('#photos').click(function() {
var path = $(this).attr('src');
});
Upvotes: 0