Micheal
Micheal

Reputation: 133

Delete single item using Ajax and jQuery

Please I need to delete item from my website using jQuery and ajax but I don't know how to get the particular id of what I want to delete or less is single see below example:

HTML CODE

<span id="file-1">Orange</span> <a id="delete-1">Delete</a>
<span id="file-2">Orange</span> <a id="delete-2">Delete</a>
<span id="file-3">Orange</span> <a id="delete-3">Delete</a>
<span id="file-4">Orange</span> <a id="delete-4">Delete</a>
<span id="file-5">Orange</span> <a id="delete-5">Delete</a>
<!--Next item will have id of 6 is looping...-->

AJAX JQUERY

<script>
    $(document).ready(function(e){
        $("#delete-").click(function(){
//Am confused here how to know which id need to be deleted?
var id = $('#file-').val();
        $.ajax({
        url:'/delete_reply.php',
        data:'id='+id,
        type: "POST",
        beforeSend: function(){
        $('#comment-'+id'').attr('class', 'deleting');
        },
        success: function(data){
            $('#comment-'+id'').hide();
            $(#comment-'+id'').css('display','none'); 

        }
          });
          });
    });
</script>

Please I don't know how to pass the id of the content I want to delete to the ajax can someone help me?

Upvotes: 1

Views: 2707

Answers (2)

Alok Patel
Alok Patel

Reputation: 8022

UPDATE:

It's good approach to assign value to HTML element using data attributes.
For that HTML and jQuery both would look something like follow.

HTML:

<span id="file-3">Orange</span> <a data-fileid="3" class="cmnDeleteFile">Delete</a>

JQUERY

$(".cmnDeleteFile").click(function(e){
    e.preventDefault();

    var id=$(this).data('fileid');
    // This is how you get id of the file from same element using data attribute.

});

Old answer:

You're following wrong method. Give every link common CSS class and fire trigger event on click of a link like this.

HTML:

<span id="file-3">Orange</span> <a id="3" class="cmnDeleteFile">Delete</a>

JQUERY

$(".cmnDeleteFile").click(function(e){
    e.preventDefault();

    var id=$(this).attr('id');
    // This is how you get id of the file from same element.

});

Upvotes: 3

Niks
Niks

Reputation: 4832

Replace your

var id = $('#file-').val();

with

var id=$(this).attr('id').split("-")[1];

Btw, I haven't tested rest of your code. Particularly, your #delete- selector that you have used for binding click event.

Upvotes: 1

Related Questions