0

I'm really stuck with this :(

I'm trying to echo function inside Ajax function with foreach loop for a list of users!

To be clear: I have a list of followers/following users inside author.php, Then i have created Ajax pagination for them with load more button.

I'm using " Users Following System " plugin, Below you can find that function for displaying the follow button link, then i echo that function like that echo pwuf_get_follow_unfollow_links( $user->ID ); inside the Ajax pagination template.

I used this before with another users paged template it working without any problems!

But when i trying to add inside Ajax function not working, when i click on the (follow button) it jumping to the top of page?

I tried to add #! to href="#!" link, the page stopped from jumping to top but still the follow button not working!

Console and debugging is clear! So what i'm doing wrong?

Here are all my code and i hope to find what's wrong with,

display-functions.php of the follow button.

function pwuf_get_follow_unfollow_links( $follow_id = null ) {

    global $user_ID;

    if( empty( $follow_id ) )
        return;

    if( ! is_user_logged_in() )
        return;

    if ( $follow_id == $user_ID )
        return;

    ob_start(); ?>
    <div class="follow-links">
<?php
if ( pwuf_is_following( $user_ID, $follow_id ) ) {
    $classes = "unfollow";
    $text = "Following";
} else {
    $classes = "follow";
    $text = "Follow";
}
?>
<span><a href="#" class="<?php echo $classes; ?>" data-user-id="<?php echo $user_ID; ?>" data-follow-id="<?php echo $follow_id; ?>"><span><?php echo $text; ?></span></a></span>
<img src="<?php echo PWUF_FOLLOW_URL; ?>/images/loading.svg" class="pwuf-ajax" style="display:none;"/>
    </div>
    <?php
    return ob_get_clean();
}

Ajax actions of the follow/unfollow button

/**
 * Processes the ajax request to follow a user
 *
 * @access      private
 * @since       1.0
 * @return      void
 */

function pwuf_process_new_follow() {
    if ( isset( $_POST['user_id'] ) && isset( $_POST['follow_id'] ) ) {
        if( pwuf_follow_user( absint( $_POST['user_id'] ), absint( $_POST['follow_id'] ) ) ) {
            echo 'success';
        } else {
            echo 'failed';
        }
    }
    die();
}
add_action('wp_ajax_follow', 'pwuf_process_new_follow');


/**
 * Processes the ajax request to unfollow a user
 *
 * @access      private
 * @since       1.0
 * @return      void
 */

function pwuf_process_unfollow() {
    if ( isset( $_POST['user_id'] ) && isset( $_POST['follow_id'] ) ) {
        if( pwuf_unfollow_user( absint( $_POST['user_id'] ), absint( $_POST['follow_id'] ) ) ) {
            echo 'success';
        } else {
            echo 'failed';
        }
    }
    die();
}
add_action('wp_ajax_unfollow', 'pwuf_process_unfollow');

wp_enqueue_script for follow.js

/**
 * Loads plugin scripts
 *
 * @access      private
 * @since       1.0
 * @return      void
*/

function pwuf_load_scripts() {
    wp_enqueue_script( 'pwuf-follow', PWUF_FOLLOW_URL . 'js/follow.js', array( 'jquery' ) );
    wp_localize_script( 'pwuf-follow', 'pwuf_vars', array(
        'processing_error' => __( 'There was a problem processing your request.', 'pwuf' ),
        'login_required'   => __( 'Oops, you must be logged-in to follow users.', 'pwuf' ),
        'logged_in'        => is_user_logged_in() ? 'true' : 'false',
        'ajaxurl'          => admin_url( 'admin-ajax.php' ),
        'nonce'            => wp_create_nonce( 'follow_nonce' )
    ) );
}
add_action( 'wp_enqueue_scripts', 'pwuf_load_scripts' );

follow.js

jQuery(document).ready(function($) {
    /*******************************
    follow / unfollow a user
    *******************************/
    $( '.follow-links a' ).on('click', function(e) {
        e.preventDefault();

        var $this = $(this);

        if( pwuf_vars.logged_in != 'undefined' && pwuf_vars.logged_in != 'true' ) {
            alert( pwuf_vars.login_required );
            return;
        }

        var data      = {
            action:    $this.hasClass('follow') ? 'follow' : 'unfollow',
            user_id:   $this.data('user-id'),
            follow_id: $this.data('follow-id'),
            nonce:     pwuf_vars.nonce
        };

        $this.closest('.follow-links').find('img.pwuf-ajax').show();

        $.post( pwuf_vars.ajaxurl, data, function ( response ) {
            if ( response == 'success' ) {
                if ( $this.hasClass( 'follow' ) ) {;
                    $this.removeClass( 'follow' ).addClass( 'unfollow' );
                    $this.find( 'span' ).text( 'Unfollow' );
                } else {;
                    $this.removeClass( 'unfollow' ).addClass( 'follow' );
                    $this.find( 'span' ).text( 'Follow' );
                }
            } else {
                alert( pwuf_vars.processing_error );
            }
            $this.closest('.follow-links').find('img.pwuf-ajax').hide();
        });
    });
});

And this is the Ajax pagination template for the following users.

add_action('wp_ajax_user_following_by_ajax', 'user_following_by_ajax_callback');
add_action('wp_ajax_nopriv_user_following_by_ajax', 'user_following_by_ajax_callback');

function user_following_by_ajax_callback()  {

    check_ajax_referer('user_more_following', 'security');
    $paged = $_POST['page'];

    /// detect the author data with the name or with the author id
    $curauth = NULL;

    if( isset($_POST['author_name']) AND trim($_POST['author_name']) != '' ) {

        $curauth = get_user_by('slug', trim($_POST['author_name']) );

    } elseif( isset($_POST['author']) AND intval($_POST['author']) > 0 ) {

        $curauth = get_userdata( intval($_POST['author']) );    

    }

    if( !is_null($curauth) ) {

        $include = get_user_meta($curauth->ID, '_pwuf_following', true);

        if ( empty( $include ) ) {

    echo '<div class="no-follower">Not found followers yet <i class="fa fa-slack fa-1x" aria-hidden="true"></i></div>';

        } else {

            $args = array (
                'order' => 'DESC',
                'include'  => $include,
                'number'  => '20',
                'paged' => $paged
            );

    $wp_user_query = new WP_User_Query( $args );

    $users = $wp_user_query->get_results();

    foreach ( $users as $user ) {

        $avatar = get_avatar($user->user_email, 100);
        $author_profile_url = get_author_posts_url($user->ID);
        $profile = get_userdata($user->ID);

    echo '<div class="members-name-9"><a href="', $author_profile_url, '">' . $profile->first_name .'</a>';

    echo '<a href="', $author_profile_url, '">', $avatar , '</a>';

    echo pwuf_get_follow_unfollow_links( $user->ID );

    }

    echo '</div>';

    }

  } else {

      echo '<div class="no-follower">Not found followers yet <i class="fa fa-slack fa-1x" aria-hidden="true"></i></div>';
      }

    wp_die();
}

Load more button Script.

<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
    $('body').on('click', '.loadmorefollowing', function(e) {
        e.preventDefault();

            var data = 
            {
                'action': 'user_following_by_ajax',
                'page': page,
                'security': '<?php echo wp_create_nonce("user_more_following"); ?>',
                'author': '<?php echo esc_html($curauth->ID); ?>'

            };

    $.post(ajaxurl, data, function(response) {

                if ( '' === response ) {
                    $('.loadmorefollowing').hide();
                        $('.nomorefollowing').show();
                    return;
                }

        $('#following-artists-cont').append(response);
        page++;
    });
    });
});
</script>

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.