How to delete post attachments when jQuery is used with a click event on the delete link

I have finally figured out how to do it, and it now works 100%!!

Plus it uses the admin-ajax.php so clicking the Remove link there is an ajax request sent to the function that does the deleting of the attachment and returns the message saying it has been deleted.

Here’s the code for my solution, first is the html for the metabox:

<a class="remImage" href="#"><?php _e('Remove');?></a>                  
<input type="hidden" id="att_remove" name="att_remove[]" value="<?php echo $attachment->ID; ?>" />
<input type="hidden" name="nonce" id="nonce" value="<?php echo wp_create_nonce( 'delete_attachment' ); ?>" />

Here’s the Php function:

add_action( 'wp_ajax_delete_attachment', 'delete_attachment' );
function delete_attachment( $post ) {
    //echo $_POST['att_ID'];
    $msg = 'Attachment ID [' . $_POST['att_ID'] . '] has been deleted!';
    if( wp_delete_attachment( $_POST['att_ID'], true )) {
        echo $msg;
    }
    die();
}

And the jQuery script that sends the attachment ID and action, etc., then removes the div from the DOM after receiving the ajax response is:

    jQuery('.remImage').live('click', function() {
        if( size > 1 ) {
            jQuery.ajax({
                type: 'post',
                url: ajaxurl,
                data: {
                    action: 'delete_attachment',
                    att_ID: jQuery(this).parents('.attchmt').find('#att_remove').val(),
                    _ajax_nonce: jQuery('#nonce').val(),
                    post_type: 'attachment'
                },
                success: function( html ) {
                    alert( html );
                }
            });
            jQuery(this).parents('.attchmt').detach();
            size--;
        }
        return false;
    });

I am now able to finally complete what I thought was totally impossible after the number of attempts I’ve made in trying to make it and have failed each time.

It will soon be a plugin, that I can then use on any site easily, with simple options to define the post type to add it to.