1

Yes, it's another csrf question, the standard, 400 Error - Bad Request: Unable to verify your data submission.

If in config/general.php I set 'enableCsrfProtection' => false, then everything works nicely. So it's definitely a csrf problem.

Here's the twig template for the widget:

src/templates/_components/widgets/Livestream_body.twig
---------------------
<script type="text/javascript">
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
</script>

and the Javascript:

src/assetbundles/livestreamwidget/dist/js/Livestream.js
-------------------
$(document).ready(function () {
   var data = [];
   data[window.csrfTokenName] = window.csrfTokenValue;
   $.post('actions/livestream/main/manage-get', data, function(response, textStatus, jqXHR) {
       alert('Posted OK!'); 
   });
});

I can see the csrf token value changes on page load, and as I said, without csrf enabled, the js successfully loads the widget, so, what am I doing wrong on the csrf? I don't have any element. Would that make a difference?

  • what happen if you wrap your js code in document.ready? maybe request is sent before variable assignment in twig? – user9975 Apr 2 at 19:27
  • @user677900 Sorry, it is. I showed that in the question now. – kr37 Apr 2 at 19:31
  • with developer tools in FF, can you see csrf param sent for that request and is it as same as window.csrfTokenValue and window.csrfTokenName in inspector tab? – user9975 Apr 2 at 19:36
  • @user677900 I can see window.csrfTokenValue/Name but the params tab is blank. It says "No parameters for this request." – kr37 Apr 2 at 19:48
  • 1
    Thank you so much, kind person. I've been fighting with this for three days, and now it works! If you want to post a solution, I'll accept it. – kr37 Apr 2 at 20:29
2

as jQuery docs says you have to pass data object or string via data. so you should change

var data = [];

to

 var data = {};

in your code

| improve this answer | |

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.