I'm trying to implement WP AJAX in one of my Under-dev Plugin after successful implementation in WP Theme.
function deactivate_ad() {
if( isset( $_POST['id'] ) ) {
echo $_POST['id'];
echo 'Deactivated';
die;
} else {
echo 'Sorry, not done';
die;
}
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
add_action('wp_ajax_deactivate_ad', 'deactivate_ad');
//add_action( 'wp_ajax_nopriv_deactivate_ad', 'deactivate_ad'); //not logged in users
And beneath the function somewhere, I added my form with dynamic ID:
<form action="" enctype="multipart/form-data" method="post">
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).on('click', '.deactivate-ad', function () {
var id = this.id;
alert(id);
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
"action": "deactivate_ad",
"id": id
},
success: function (data) {
alert(data);
}
});
});
</script>
<?php
//after the db Query, within the foreach loop
foreach( $ad_query as $the_ad ){
$element_id = 'deactivate_' . $the_ad->id . '_' . wp_create_nonce('deactivate_' . $the_ad->id );
// I'm just checking with the 'Deactivate' button first
echo ( $the_ad->ad_status == 1 ? '<a class="deactivate-ad" href="#" id="'. $element_id .'">Deactivate</a>' : '<a href="?page=site-ad&id='. $the_ad->id .'&activate=true&success=true">Activate</a>' );
}
?>
</form>
I'm just trying to activate the AJAX so that I can do whatever I want then. But with first alert(id)
I can alert the id
with nonce successfully, but the alert(data)
it's always returning 0
(zero).
I am enqueueing the latest jQuery (http://code.jquery.com/jquery-latest.min.js) at the beginning and checked all the instances. What am I doing wrong this time - the process I acquired worked in a theme - I worked earlier.