This part of the User Follow System tutorial series will focus on writing the necessary javascript for trigger the follow/unfollow actions. When a follow or unfollow link is clicked, the javascript will trigger an ajax action that then talks to the server and tells it which user is being followed or unfollowed, and which user is doing the following or unfollowing.

Before we write our actual javascript, we need to load it. This is done from our includes/scripts.php file. The wp_enqueue_script and wp_localize_script functions will be used for loading our javascript:

<?php
 
/**
 * 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' );

The js/follow.js fille will hold all of our javascript. If you have not already, go ahead and create the file.

wp_localize_script is used to make our localized (for translation) error messages available to our javascript, as well as making it possible for our javascript to detect if the current user is logged in or out. It also provides us with the URL to the admin-ajax.php file, which is used for processing ajax requests in WordPress. If you’re not familiar with this function, I’d suggest reading my tutorial on it.

Our follow.js javascript file will now be loaded on every page of the site. Note: if you know that your follow/unfollow links will only be present on specific pages (perhaps user profile pages) then you should only load the script on those pages for performance reasons.

Before we write the javascript, let’s quickly run through how the process works.

As we know from Part 4, our user profiles have a set of links on them for following or unfollowing a user. If you (the logged-in user) is already following said user, you will see a link that says “Unfollow”. If you are not already following the user, then you will see a link that says “Follow”.

When one of the links is clicked, our javascript will look at the class attribute of the link. If the link has the “follow” class, it means we are attempting to follow a user, otherwise we are unfollowing a user.

Once the appropriate action has been detected and set, an ajax call to the server is fired. The call includes the user ID doing the following and the user ID being unfollowed. The server will then process the request and send back a response. If the response is “success”, meaning the user follow status has been successfully updated, we use javascript to swap the links (to allow the user to undo the action they just took).

Here is our complete javascript:

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
		};
 
		$('img.pwuf-ajax').show();
 
		$.post( pwuf_vars.ajaxurl, data, function(response) {
			if( response == 'success' ) {
				$('.follow-links a').toggle();
			} else {
				alert( pwuf_vars.processing_error );
			}
			$('img.pwuf-ajax').hide();
		} );
	});
});

The next part of the tutorial series will cover processing the actual ajax requests.

Join now to gain access to this tutorial and more.

Join Now
  1. Amer Abdul

    Thanks Pippin for this amazing tutorial, and wondering how can I find the Part 6 of this series?

  2. Dasha Luna

    Hey Pippin,

    Thanks for the series, I’m learning lots of things!

    I’m still pretty new to javascript though. I was wondering if you could add a step by step explanation of javascript code in this tutorial similar to how you’ve got step by step code explanation for PHP functions in earlier tutorials.

    That would be really helpful.

    Many thanks,
    Dasha

    • Pippin

      Thanks for the suggestion! Could you tell me which part of the JS is unclear to you so I can try and assist you?

Error: Please enter a valid email address

Error: Invalid email