0

I'm trying to make a simple post request with ajax to a controller in plugin. The problem I'm having is that I always get a 400 Bad request because I don't send a valid CSRF Token.

But I can't figure out how to get this in javascript. I found multiple examples saying you get it by calling

Craft.getCsrfInput();

but this only works in "CP mode", on the front-end the Craft object is not available. I also found that importing it is not a good idea.

So anyone who can tell me how to do this?

2

You can take a look at the guide Enabling CSRF Protection

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
</script>
var data = {
    // ...
};

// Add the CSRF Token
data[csrfTokenName] = csrfTokenValue;

$.post('/some/url', data, function(response, textStatus, jqXHR) {
    // ...
});
  • Thank you, just what I was looking for. Strange that I didn't came across these guides, is it just me or is the Craft documentation a bit all over the place? – dazz Feb 21 at 11:23
  • The Craft documentation became way better in the last month and when you know where you need to search you can get your information quite good. But the best place is still the source code – Robin Schambach Feb 21 at 11:26

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.