I have an array within the post meta for a post. I want to be able to list out each individual element of the array in the admin area and delete a value from that array.
I currently loop over each of my array elements and attempt to use ajax to delete them, when I click on the delete button it sends the value to my ajax action, I then load the post meta I want, remove the value and then update the post meta. However my console.log(data) brings back 0 every time and doesn't fade the div. Can anyone see why?
function print_pdfs_attached() {
global $post;
$attached_pdfs = get_post_meta( $post->ID, 'pdf_upload_url', true ); ?>
<p>All PDFs attached to the article</p>
<?php
$i=0;
if($attached_pdfs) {
foreach($attached_pdfs as $pdf) { ?>
<div id=<?php echo $pdf; ?>>
<p><?php echo $pdf; ?></p>
<input type="hidden" value="<?php echo $pdf; ?>" id="ajaxtestdel_postid<?php echo $i ?>">
<tr>
<th scope="row"><label for="del">delete</label></th>
<td><input type="button" name="del" id="del<?php echo $i; ?>" value="delete" class="button"></td>
</tr>
<script>
jQuery('#del<?php echo $i; ?>').on('click', function(){
var post = jQuery('#ajaxtestdel_postid<?php echo $i ?>').val(); // get post id from hidded field
console.log(post);
jQuery.ajax({
url: 'admin-ajax.php', // in backend you should pass the ajax url using this variable
type: 'POST',
data: { action : 'ajaxtestdel', postid: post },
success: function(data){
console.log(data);
jQuery("#<?php echo $pdf; ?>").fadeOut( "slow" );
}
});
});
</script>
<?php
$i++;
?>
</div>
<?php
}
}
else { ?>
<p>No PDFs are currently attached to this article</p> <?php
}
}
function ajaxtestdel(){
global $post;
$currentPdfs = get_post_meta( $post->ID, 'pdf_upload_url', true );
$postValue = isset($_POST['postid']) ? $_POST['postid'] : '';
$array_without_strawberries = array_diff($currentPdfs, array($postValue));
update_post_meta( $post->ID, 'pdf_upload_url', $array_without_strawberries );
}
add_action('wp_ajax_ajaxtestdel', 'ajaxtestdel');