Ajax with WordPress update_post_meta always giving 0 with response

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

Read More
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);
}

Related posts

Leave a Reply

2 comments

  1. 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.

    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(){
        $post_id=$_POST['post_id'];
        $post_status=$_POST['status'];
        $edit_key = '_edit_status';
        if ( ! update_post_meta ( $post_id, $edit_key, $post_status) ) { 
            add_post_meta( $post_id, $edit_key, $post_status, true );   
        }; 
    }