Getting Comment Count Based on URL

Hi All,

In one of our news listing web part we have requirement to show the comments count for given news. On news pages we are using the NoteBoard web part for commenting purpose.

For news listing we are using OOB Content by Search (CBS) web part and in front of news title we need to show the comment count.

Since we are using OOB web part we don’t have an option of code where we can create SocialCommentManager class and call GetCount(Uri) method. The other option is to use the SocialDataService (SocialDataService.asmx) and call this from the display template of CBS web part. This solution is also compatible with Office 365.

Following is the sample script:

  1. function ReturnCommentsCount(url) {   
  2.      var dataXML = GenerateDataXML([url]);   
  3.      $.ajax({   
  4.          url: "/_vti_bin/SocialDataService.asmx?op=CountCommentsOnUrl",   
  5.          data: dataXML,   
  6.          type: "POST",   
  7.          async: true,   
  8.          complete: processResult,   
  9.          contentType: "text/xml; charset=utf-8",   
  10.          dataType: "xml"   
  11.      })   
  12.    
  13.      //Following function generates the require soap XML   
  14.      function GenerateDataXML (url) {   
  15.          var soapXml = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +   
  16.          "<soap:Body>" +   
  17.          "<CountCommentsOnUrl xmlns=\"http://microsoft.com/webservices/SharePointPortalServer/SocialDataService\">" +   
  18.          " <url>" + url + "</url>" +   
  19.          "</CountCommentsOnUrl>" +   
  20.          "</soap:Body>" +   
  21.          "</soap:Envelope>"   
  22.          return soapXml;   
  23.      }   
  24.    
  25.      function processResult(content, txtFunc, xhr) {   
  26.          // Here we get the actual comment count   
  27.          //We can set this to any span element   
  28.          var commentsCount = $(content.responseText).find('CountCommentsOnUrlResult').text();   
  29.      }  
Finally from display template we can directly call ReturnCommentsCount(news url) and set the comment count to HTML element in front of news title like for example consider <span> element having id "commentcount" so like: 
  1. $("#commentcount”).text(commentsCount);  

Complete processResult method will be like: 

  1. function processResult(content, txtFunc, xhr) {   
  2.      // Here we get the actual comment count   
  3.      //We can set this to any span element   
  4.      var commentsCount = $(content.responseText).find('CountCommentsOnUrlResult').text();   
  5.      $("#commentcount”).text(commentsCount);   
  6.  }  
Thanks! 

Enjoy reading
 
Feel free if any comment / question.