0

I have a follow users system here's my simplify codes.

Javascript code:

$(document).on('click', '.follow-user',function(){
   follow_to    =   $(this).data('follow-user');

   $('[data-follow-user="' + follow_to + '"]').each(function() {
       $(this).find('.follow-txt').html('Unfollow');
   });

   $.ajax({
       url: site_globals_info.ajaxURL,
       type: "POST",
       data: {
           action : 'follow_users_system',
           follow_to : follow_to,
           follower : currentUserInfo.ID
       }
   });
});

PHP Code:

add_action("wp_ajax_follow_users_system", "follow_users_system" );
add_action("wp_ajax_nopriv_follow_users_system", "follow_users_system" );
function follow_users_system(){
    global $user, $current_user;
    $follower = $_REQUEST['follower']; 
    $follow_to = $_REQUEST['follow_to']; 

    $get_following_users = get_user_meta($follower, "the_following_users", true);

    if(in_array($follow_to, $my_following_users) && is_array($my_following_users)){
        // You are already following this user
    } else {
        $get_following_users[] = $follow_to;
    }

    update_user_meta($follower, "the_following_users", $get_following_users);


    wp_send_json_success();
    wp_die();
    exit();
}

The system is working but the issue that if I follow more than one user at the same time the system is store only one user into the_following_users meta.

What Must I do to prevent this issue? I must wait until the ajax request is finished and then follow the anther user.

NOTE: To test this please add a follow button for 5 users and try to follow each user at the same time without waiting for any ajax request to be finished and you will meet the issue.

  • your if is not correct, if the user is already in the array, the else part is run and the array is erased. – mmm Jan 7 '18 at 11:05
  • @mmm I edited the code but that does not solve the problem if you have a solution for this issue please write the correct code in a new answer. – Michel Jan 7 '18 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.