I’m trying to do update_post_meta function using Ajax and trying to pass value to database when the toggle is changed. But when Ajax is ran it always producing 0 as the response. Code is below please let me know where should i rectified.
jQuery
jQuery('.completed').change(function() {
post_id = jQuery(this).data('postid');
if(this.checked) {
var status = "on";
} else {
var status = "off";
}
jQuery.ajax({
url: wpb_ajax_url,
data: 'action=switch_toggle_post&post_id='+post_id+'&status='+status,
dataType: 'JSON',
type: 'POST',
success:function(data){
alert('Saved');
}
});
});
PHP
/* switch Toggle */
add_action('wp_ajax_nopriv_switch_toggle_post', 'switch_toggle_post');
add_action('wp_ajax_switch_toggle_post', 'switch_toggle_post');
function switch_toggle_post(){
add_post_meta( $post_id, '_edit_status', $status, true ) || update_post_meta( $post_id, '_edit_status', $status);
}
Replace the url code with the below code
Issue here was i missed to retrieve variables passed in ajax in the php function. Finally managed to get it sorted changing the PHP code as follows.