简体   繁体   中英

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?

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.

});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM