0

I am trying to update a custom field for a custom post type with this function php

add_action('wp_ajax_updatemeta', 'toggle_task_status');
add_action('wp_ajax_nopriv_updatemeta', 'toggle_task_status');
function toggle_task_status () {
    $post_id = $data['post_id'];
    return update_post_meta($post_id , 'task_status', 'open');
}

javascript


jQuery("form").on("submit", function () {
    console.log("hello");
    var post_id = jQuery("#post_id").val();
    console.log(post_id);
    var post_data = {
                    action: "updatemeta",
                    data: {
                        post_id: post_id,
                    }
                };
    jQuery.ajax({
        type: "POST",
        url: "http://cloud-accounting.com/wp-admin/admin-ajax.php",
        data: post_data,
        dataType: "json",
        cache: false,
        error: function (jqHXR, textStatus, errorThrown) {
            console.error("it is not working   "+textStatus, errorThrown);
        },
        success: function () {
            console.log("it is working");
        }
    
    })
})

and the code gives me success but it doesn't work , I see the same before and after the request

1
  • Ypu're not passing $data to toggle_task_status() function Commented Feb 28, 2022 at 12:40

1 Answer 1

0

I don't think you're actually getting the post ID sent by the javascript.

function toggle_task_status () {
    $post_id = $_POST['data']['post_id'];
    $update = update_post_meta($post_id , 'task_status', 'open');
    if($update){
        wp_send_json('success');
    } else {
        wp_send_json('fail');
    }
    wp_die();
}

and then in your javascript

success: function (response) {
    console.log(response); // should be either 'success'  or 'fail'
}
2
  • Thank you very much , you saved me Commented Feb 28, 2022 at 23:08
  • You're very welcome :)
    – MikeeeG
    Commented Mar 16, 2022 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.