0

I have the list called comments, I'm displaying those comments list item on page using JSOM. Now I have enabled likes for the list

I'm trying to use like list item functionally on a page to like particular comments list item. Also, I have to show all list item likes on page also

  • Is server side code is OK for you? We have implemented same functionality using data service class which is called by ajax and updating item using Reputation OOTB class. I'll provide you with sample if this is OK for you, Andrew. – Andrew Adamich Sep 14 '17 at 10:49
0

We have achieved this using server side list item update using OOTB Reputation class from Microsoft.Office.Server.ReputationModel.

To do this:

  1. In _layouts ("Layouts" mapped folder) create new application page which will serve AJAX methods.

  2. Create method "LikeItem"

This method will be called from AJAX to execute server side logic:

[WebMethod(EnableSession = false)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static bool LikeItem(string itemId)
{
   try
   {
      if (string.IsNullOrEmpty(itemId)) return false;

      int item;
      var isIdPassed = int.TryParse(itemId, out item);

      if (!isIdPassed) return false;

      // Get list to like item in
      var list = SPContext.Current.Site.RootWeb.Lists.TryGetList(<List title>);

      // Set
      Reputation.SetLike(list.ID.ToString(), item, true);

      return true;
   }
   catch (Exception ex)
   {
      return false;
   }
}

From JS call the method:

var executeOptions = {
   type: "POST",
   url: "/_layouts/DataService.aspx/LikeItem",
   data: "{itemId: '" + <id of the item> + "' }",
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   headers: {
      "X-RequestDigest": $("#__REQUESTDIGEST").val()
   },
   xhrFields: { withCredentials: true }
};

$.ajax(executeOptions).then(function (content) {
   if (!content.d) {
      // Handle errors here
   }

   // success - do your logic here
});

Hope this helps,

Andrew

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.