Numeric response from a .post() request is adding

2019-07-29 08:53发布

I'm using the Wordpress ajax api to send the result of a php function to the client with .post() ajax. The problem is the value returning a 0 aswell as the numeric value. So if the numeric value is "3" I get "30".

So here I have a php function that I use to grab the user_id and return the corresponding unseen comment count for that user.

 add_action("wp_ajax_return_unseen_comment_count","return_unseen_comment_count");
 function return_unseen_comment_count() {
    $user_id = $_POST['userId'];
    $count = get_unseen_comment_count($user_id);
    echo $count;
 }

If I place the word "test" after $count I'll get "3test0".

I then use an interval to check function for new unseen comments.

$(document).ready(function() {
    var userId = fodAjax.user_id;
    var cmntCount = $(".cmnt-cnt").text();
    if (userId > 0) {
      setInterval(function() {
               data = {
                  action: 'return_unseen_comment_count',
                  userId: userId
               };
               $.post(ajaxurl, data, function (response) {  
                  console.log(response);                  
               });
      }, 10000); //10 seconds
    }
});

Now I use get_unseen_comment_count($user_id) in another function to display the count in my template and it returns the correct value "3" so it's not doing anything extra that should be adding the 0. What am I missing here?

1条回答
Lonely孤独者°
2楼-- · 2019-07-29 09:17

You must write exit; after echo statement.

If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed. Additionally, if an AJAX request succeeds, it will return a 0.

Reference.

查看更多
登录 后发表回答