How do you create an attachment ID with Ajax submit? No page refresh

Here’s my solution for creating an attachment ID with a temporary title and the post_parent which it is attached to.

My jQuery psuedo code, without the needless stuff:

    jQuery('.addImage').live('click', function() {
        jQuery.ajax({
            type: 'post',
            url: ajaxurl,
            data: {
                action: 'save_attachment',
                _ajax_nonce: jQuery('#nonce_add').val(),
                post_parent: jQuery('#post_ID').val(),
                attach_title: 'Attachment ' + size
            },
            success: function( res ) {
                var attID = res.replace(/0$/i, '');
                alert('Success: ' + attID);
            }
        });             
        size++;
        return false;
    });

My admin-ajax.php function and custom hook:

function save_attachment() {
    if ( $_POST['action'] == 'save_attachment' ) {

        $post_title = $_POST['attach_title'];
        $post_parent = $_POST['post_parent'];

        $attach = array(
            'post_title'    => $post_title,
            'post_parent'   => $post_parent,
            'post_type'     => 'attachment',
            'guid'          => '',
            'post_mime_type'=> 'image'
        );
        $attachID = wp_insert_attachment( $attach, false );
        if( $attachID ) {
            print_r( $attachID );
        }
    }
}
add_action( 'wp_ajax_save_attachment', 'save_attachment' );

See what I have here is, there’s a link with class .addImage, you click that, and it runs the ajax/php save_attachment() function returns the ID which i use in the chunk of code I prepend to my metabox (a group of inputs for new file) and the attachment ID returned is used as the value in the hidden input field within that chunk of code. There’s also a save button in that chunk.

Now, given that ID, i can use my already complete and working function for saving (or updating) the attachments with admin-ajax.php saving the data entered and file selected for each one. The remove button for each is also able to make use of the ID to remove the blank attachments if you have no use for them.

This will soon be a sick ass plugin, once i get this working as a-jacksed up custom metabox.