doublesecretagency / craft-viewcount

View Count plugin for Craft CMS
Other
6 stars 4 forks source link

Increment via AJAX as per docs causes error #29

Open splendidrob opened 1 year ago

splendidrob commented 1 year ago

Hey there!

I'm finding an error when trying to increment the counter on clicking a button ass per the instructions in the docs.

My JS:

/*
  VIEWCOUNT
  AJAX to increment views via the View Count plugin
*/

var viewcount = function() {

  var $triggers = $('[data-viewcount-increment]');

  if (!$triggers.length) { return; }

  console.log('viewCount.init');

  // FN: INCREMENT COUNT
  function incrementView(elementId, key) {

    // Set view data
    var data = {
      'id': elementId,
      'key': key
    };

    // Append CSRF Token
    data[window.csrfTokenName] = window.csrfTokenValue;

    // Render search results
    $.post(
      '/actions/view-count/increment',
      data,
      function (response) {
        console.log('viewCountIncrement',response);
      }
    );
  };

  // TRIGGER
  $triggers.on('click', function (e) {
    var $currentTrigger = $(this);
    var targetId = $currentTrigger.attr('data-viewcount-increment');

    incrementView(targetId);
  });

};

Results in a 404: screenshot_1252

Many thanks for any help!

splendidrob commented 11 months ago

Any help on this...still havent managed to get anything to work incrementing on click. I realised the action above wasn't the correct url but even then I still get the following:

screenshot_1275

lindseydiloreto commented 11 months ago

Hi @splendidrob, glad you got the path issue sorted out! 👍

A 400 (Bad Request) error is usually an indication that the CSRF token isn't being set properly. Check to make sure that the data array is configured as expected before the AJAX call is made.

If you're still stuck, feel free to hit me up on Discord, where we can work through it together in real-time.