Jesse Elser
Jesse Elser

Reputation: 976

Jquery Remove Element After Deletion From Server

I'm working on a function that deletes images from my gallery. On the PHP side it works. With Jquery/Ajax it also works. But when I modified my jquery to remove the element when the image gets deleted(remove the element client side) it no longer works(when I say no longer works it is giving me the error function built into the code:

This code works:

function deleteImage(file_name)
{
    var r = confirm("Are you sure you want to delete this Image?")
    if(r == true)
    {
        $.ajax({
          method: "POST",
          url: '/images/gallery/deleteImage.php',
          data: {'delete_file' :  file_name },
          success: function (response) {
             ohSnap("Image has been deleted.", "green");
          },
          error: function () {
             ohSnap("An error has occured.", "red");
          }
        });
    }
}

But this one doesn't

function deleteImage(file_name)
{
    var r = confirm("Are you sure you want to delete this Image?")
    if(r == true)
    {
        $.ajax({
          method: "POST",
          url: '/images/gallery/deleteImage.php',
          data: {'delete_file' :  file_name },
          success: function (response) {
             $('#' + file_name).remove();
             ohSnap("Image has been deleted.", "green");
          },
          error: function () {
             ohSnap("An error has occured.", "red");
          }
        });
    }
}

Any idea why adding the remove function is causing an error? In console it is not telling me why, so I'm lost.

UPDATE:

Here is an example of one of the elements:

<div class="thumbImage" id="happy_anime_s2-1433126427.png">
<a href="images/gallery/happy_anime_s2-1433126427.png" data-featherlight="image">
<img src="images/gallery/happy_anime_s2-1433126427.png" width="200px" alt="" />
</a>
<span class="deleteImage">
<input type="hidden" value="happy_anime_s2-1433126427.png" name="delete_file" id="delete_file" />
<input type="button" value="Delete image" onclick="deleteImage('happy_anime_s2-1433126427.png');"/>
</span>
</div>

Upvotes: 1

Views: 117

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The problem is the . in the id, which creates a class selector. Looks at the selector #happy_anime_s2-1433126427.png, it looks for an element with id happy_anime_s2-1433126427 and has a class png.

You need to escape the . using \\. like

$('#' + file_name.replace('.', '\\.')).remove();

selectors

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \.

Upvotes: 2

Related Questions