3

I'm writing a plugin to notify authors when a Disqus comment is posted. There is a Disqus JS callback you can use to hook into this, so I'm doing the following on the front-end:

this.callbacks.onNewComment = [function(comment) {
  var commentNotification = new window.VIGET.CommentNotification();

  commentNotification.notify('{{ actionUrl("vigetDisqus/notify/notify") }}', comment, {{ entry.id }}, {{ entry.author.id }});
}];

So I am passing the actionUrl of my controller, the comment itself, the entry id, and the author id. This all works perfectly fine, and I am passing it as data along as an AJAX request to the controller.

CommentNotification.prototype = {
  notify: function(actionUrl, comment, entryId, authorId) {
    var data = JSON.stringify({
      comment: comment,
      entryId: entryId,
      authorId: authorId
    });

    xhr({
      uri: actionUrl,
      method: 'POST',
      body: data,
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      }
    }, function(err, resp) {
      console.log(resp.body)
    });
  }
};

How do I access the posted data inside my controller? I thought I could use the getPost method, but I am always getting null.

<?php
namespace Craft;

class VigetDisqus_NotifyController extends BaseController
{
    protected $allowAnonymous = true;

    public function actionNotify()
    {
        $this->requirePostRequest();
        $this->requireAjaxRequest();

        $authorId = craft()->request->getPost('authorId');

        $this->returnJson(array('authorId' => $authorId));
    }
}

1 Answer 1

2

Turns out the ajax library I was using was expecting the data to be passed in a serialized format:

'comment=' + comment + '&entryId=' + entryId + '&authorId=' + authorId

With that as the body of the request, the data became accessible to my controlled by using craft()->request->getPost

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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