views:

45

answers:

2

I am trying to write a simple Wordpress plugin, which updates a custom field value and increments it by one, and then echos the result which is handed back to my javascript code. For some reason, the data returned by the callback function always has an extra 0 appended to the end.

function like_post_callback() {
    $clicked = $_POST['clickedOn'];
    $id = $_POST['postID'];
    if($clicked == 0) $key = "like";
    else $key = "reallyLike";

    $prevLikes = get_post_meta($id, $key, true); //true, so we only return a single value
    $likes = 1;
    if($prevLikes == ""){
        add_post_meta($id, $key, $likes);
    } else{
        $likes = $prevLikes + 1;
        update_post_meta($id, $key, $likes);
    }

    echo $likes;
}

And here is what is calling it:

$.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", 
{ action: "like_post", clickedOn: which, postID: "<?php the_ID(); ?>"}, function(data){
    alert(data);
    $("#" + clicked).html(text + " (" + data + ")");
});

Everything works, I just have an extra 0 in data for some reason, and I don't know where it is coming from.

A: 

I needed to add die(); as the final line in like_post_callback because I needed to echo the result and stop the normal 0 return value.

jkeesh
A: 

admin-ajax always return default '0' as output. You have to use die(); to stop wordpress from calling its default function that returns zero. die(); will terminate the script returning whatever you echoed before that.

Pragati Sureka