5

How can I dynamically get the ID of the current discussion thread in javascript?
Currently, I have the following code:

function submitReply() {
    var ctx = new SP.ClientContext.get_current();
    var discussionItem = ctx.CurrentItem;
    var body = CKEDITOR.instances['commentArea'].getData();

    var messageProperties = {'Body': body}; 
    createMessage(discussionItem,messageProperties,
        function(){
            console.log('Reply has been post successfully');
        },
        function(sender,args){
             console.log('Error occurred while posting a reply:' + args.get_message());
        }
    );
}

enter image description here

When I use ctx.CurrentItem the return value is null.

enter image description here

Here is the link to my complete code: https://pastebin.com/jNFbUBaB

  • what do you mean by current discussion thread? – Atish Dipongkor - MVP Aug 25 '17 at 4:24
  • @AtishDipongkor It means that the discussion that you are viewing. – Anh Vo Aug 25 '17 at 6:25
  • line var ctx = new SP.ClientContext.get_current(); is not need. – Atish Dipongkor - MVP Aug 25 '17 at 7:57
  • just call your function like SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() { submitReply(); }); – Atish Dipongkor - MVP Aug 25 '17 at 7:58
9

You can get it from ctx. See more about ctx.

Current Discussion Item

var discussionItem = ctx.CurrentItem;

Current Discussion Item ID

var discussionItem = ctx.CurrentItem.ID;

You need to ensure that sp.js is load in the page.

SP.SOD.executeFunc('sp.js', null, function() {
   submitReply();
});

No need of line var ctx = new SP.ClientContext.get_current();

Update

If discussion thread contains any reply, then ctx.CurrentItem does not work. In that case, solution is:

var discussionItem = ctx.ListData.Row[0];

enter image description here

  • I have try this solution on my site. But the return value of ctx.CurrentItem is null. I don't know what is wrong. Could you help me with this? @AtishDipongkor – Anh Vo Aug 25 '17 at 7:35
  • 1
    call your submitReply() from SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() { submitReply(); }); – Atish Dipongkor - MVP Aug 25 '17 at 7:56
  • 1
    remove line var ctx = new SP.ClientContext.get_current(); and try – Atish Dipongkor - MVP Aug 25 '17 at 8:07
  • 1
    Ok. Then use ctx.ListData.Row[0] must work. try it instead of ctx.CurrentItem – Atish Dipongkor - MVP Aug 25 '17 at 8:40
  • 1
    That works as expected!!! – Anh Vo Aug 25 '17 at 8:57

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.