1

I'm having some trouble passing CSRF-tokens in my js-File in Craft 3.

I'm setting the values in my template like so:

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken }}";
</script>

and call them in my .js-file:

var data = {id: 100 };
    data[window.csrfTokenName] = window.csrfTokenValue;
    $.ajax({
        type: 'POST',
        url: href,
        data: data,
        success: function(result){
        },
        error: function(){
        }
    });

before i set the csrf tokens, the server returned an error 400 – bad request – as you would expect. now i'm getting a 500 internal server error. What am I doing wrong?

The site works perfect without the ajax-call so I don't think there's an issue with my templates. Tell me if you need to see more of my code.

3
  • 1
    You might want to take a look at your stack trace because a 500 states in fact the request is fine from technical frontend point of view but there is a PHP exception. Aug 20, 2018 at 21:23
  • That helped. had a misspelling in my ajax template name (started with a blank space... awesome.)
    – bstnhnsl
    Aug 21, 2018 at 8:18
  • 1
    @bstnhnsl Would you mind adding your solution as an official answer in case it ends up helping someone in the future?
    – Brad Bell
    Aug 23, 2018 at 4:07

1 Answer 1

0

As Robin Schambach suggested I looked through my stack trace. The request was fine but php couldn't find the template used on ajax-requests due to a misspelling error.

Fixed the misspelling – works like a charm.

Your Answer

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

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