1

I am trying to create an entry in a section via AJAX from the front end when not logged in. I am using the 'Guest Entries' plug in for craft to do this.

The entries are all the same and consist of only a title.

I have the whole thing working perfectly when I am logged in but not when I am logged out.

There is no form on the page as the whole thing is called via JS. The Jquery code looks like this:

var formData = [{name: "CRAFT_CSRF_TOKEN", value: "biglongtokenhere"},{name: "action", value: "guestEntries/saveEntry"},{name: "sectionId", value: "5"},{name: "title", value: "Added"}];
  $.post('/', formData , function(response) {
    if (response.success) {
      //do stuff
    }else{
      // do other stuff
    }
  });

When logged out all I get back is a 400 bad request error. Logged in as an admin it works perfectly.

The plug in is installed correctly and has a default author selected and the 'Entries Enabled by Default' slider set to true on the settings screen.

My understanding is the plugin should allow for anonymous entry submission. Thanks in advance for any suggestions.

  • A 400 Bad Request is going to be a CSRF token validation error. Just as a test, if you disable CSRF protection, does it work? craftcms.com/docs/config-settings#enableCsrfProtection – Brad Bell Aug 8 '17 at 19:03
  • Thanks for this. Disabling it works. I also read up more about how the CSRF token system works and have figured out what I was doing wrong. Cheers. – TimC Aug 10 '17 at 1:45
1

So can now answer this myself. Basically the issue is the CSRF token validation.

Options are to disable CSRF in the config.php file. Up to you how comfortable you are with that.

Or use the CSRF token properly! I thought I could set the token statically but that's not the case (which is obvious in hindsight). It is unique to each browser and is set as a cookie. To work with a pure JS set up this needs be set dynamically as a JS variable on page load. More information here: https://craftcms.com/support/csrf-protection#updating-your-javascript

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.