Adding likes functionality

Each idea in your space can accumulate “Likes” (you could call them “votes” or “recommendations” etc…)

A Like associates the current logged-in user with the idea referenced.

  • A user can only “Like” an idea once.
  • There must be a logged in current_user for a “Like” to work

As we are creating a “Like” we’ll use an HTTP POST request to a URL like this:

http://you.rusic.com/example-space/ideas/123/likes

For each idea, we’ve provided an easy way of generating this:

{{ idea.like_link }}

Example in Liquid HTML:

<a href="{{idea.like_link}}" class="js-like-idea">Like!</a>

This will not yet work because we need to attach a ‘data-idea-id’ attribute to the link to identify the ideas’ ID, as follows:

<a href="{{ idea.like_link }}" class="js-like-idea" data-idea-id="{{ idea.id }}">Like!</a>

Handling the AJAX request

In Ajax, the request is sent to the url of the clicked like link, idea.like_link. On success, it returns data and updates the html with the data-like-count attribute that contains the ideaId of the idea that was liked. In Javascript, this would look like this:

$( document ).ready(function() {
  $(".js-like-idea").on("click", function(event){
    event.preventDefault();
    var ideaId = $(this).data("idea-id");
    $.ajax({
      url: $(this).attr("href"),
      type: "POST",
      dataType: "json",
      success: function(data){
        $("[data-like-count="+ideaId+"]").text(data.likes_count);
      },
      error: function(){
        alert("Something went wrong!");
      }
    });
  });
});

As you can see, the AJAX response returns a data JSON object. For a successful “Like” this looks like:

{
  valid: true,
  likes_count: 34,
  message: "Thanks you for liking this idea!"
}

JSON definition:

  • valid - boolean true
  • likes_count - integer of number of likes, 34 is an example number
  • message - string, defined under the “Copy & text” section in the admin

If the user has already liked the idea, the JSON will look like:

{
  valid: false,
  message: "Thanks for your support, but you can only like an idea once!"
}

JSON definition:

  • valid - boolean false
  • message - string, defined under the “Copy & text” section in the admin

Removing likes

{% if idea.liked? %}
  <a href="{{ idea.like_link }}" class="js-like-idea" data-idea-id="{{ idea.id }}">Like!</a>
{% else %}
  <a href="{{ idea.like_link }}" class="js-unlike-idea" data-idea-id="{{ idea.id }}">Unlike!</a>
{% endif %}

Use an AJAX DELETE to remove the like:

(".js-unlike-idea").on("click", function(event){
    event.preventDefault();
    var ideaId = $(this).data("idea-id");
    $.ajax({
      url: $(this).attr("href"),
      type: "DELETE",
      dataType: "json",
      success: function(data){
        $("[data-like-count="+ideaId+"]").text(data.likes_count);
      },
      error: function(xhr, status, err) {
        alert("Something went wrong!");
      }
    });
  });

Page Contents

Back to top