Now you need to handle the AJAX call in PHP.
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();
}
As for your event, just add it to the click function then everything inside will know what you’re talking about.
jQuery('.remImage').on('click', function(event) {
TESTING AJAX
Copy and paste this into your functions. It will automatically run and should output a response from the AJAX in an alert and also the console.
function ajax_delete_attachment_handler() {
$data = json_encode(array('message' => 'THIS IS AJAX WORKING', '$_POST' => $_POST));
wp_send_json_success($data);
}
$action_name="delete_attachment";
add_action("wp_ajax_nopriv_$action_name", 'ajax_delete_attachment_handler');
add_action("wp_ajax_$action_name", 'ajax_delete_attachment_handler');
add_action('wp_footer', function() {
?>
<script>
jQuery.ajax({
type: 'POST',
cache: false,
dataType: 'json',
url: "/wp-admin/admin-ajax.php",
data: {
action: 'delete_attachment',
ID: 'some ID here',
'foo': 'bar'
},
success: function (response) {
// we encoded the data, so let's decode it first
var json = JSON.parse(response.data);
console.log('response: ', response);
console.log('json parsed: ', json);
alert(response.data);
},
fail: function (response) {
console.log('FAILED: ' + response);
}
});
</script>
<?php
});