Your problem is global $post
.
You have to understand that any ajax call, is a new http request, that has nothing to do with the page that send the ajax request.
If you want to pass information from the page that send the request to the page that receive the request, you have to pass the data inside the data
argument in jQuery.ajax
function.
Note that the function that print the shortcode receive the current post object as argumnet, so you can make use of it:
function testdel( $post ) { // note the $post varaible as argument
wp_nonce_field('testdel', 'ajaxsecurity'); // is a good practise adding nonces
?>
<input type="hidden" value="<?php echo $post->ID; ?>" id="ajaxtestdel_postid">
<tr>
<th scope="row"><label for="del">delete test key</label></th>
<td><input type="button" name="del" id="del" value="delete" class="button"></td>
</tr>
<script>
jQuery('#del').on('click', function(){
var $this = jQuery(this);
var post = jQuery('#ajaxtestdel_postid').val(); // get post id from hidded field
var nonce = jQuery('input[name="ajaxsecurity"]').val(); // get nonce from hidded field
jQuery.ajax({
url: ajax_url, // in backend you should pass the ajax url using this variable
type: 'POST',
data: { action : 'ajaxtestdel', postid: post, ajaxsecurity: nonce },
success: function(data){
console.log(data);
$this.val('deleted');
}
});
});
</script>
<?php
}
Now the ajax function:
function ajaxtestdel() {
$postid = isset($_POST['postid']) ? $_POST['postid'] : '';
$nonce = isset($_POST['ajaxsecurity']) ? $_POST['ajaxsecurity'] : '';
if ( $postid && $nonce && wp_verify_nonce($nonce, 'testdel') ) {
$status = delete_post_meta($postid, 'test') ? 'Error' : 'Success';
} else {
$status="Error";
}
die($status);
}
add_action('wp_ajax_ajaxtestdel', 'ajaxtestdel');
Also note that is a good practise separate js from php, so your js should go in a separate js file, enqueued in the post edit page using admin_enqueue_script
hook and wp_enqueue_script
function.