1

I am trying to send data to my plug-in controller using jquery $.post() method. here is my form:

<form method="post" action="" accept-charset="UTF-8" id="testForm">
  {{ csrfInput() }}
  <input type="hidden" name="action" value="test/test">
  <button type="submit">Test</button>
</form>

and this is my js code:

<script type="text/javascript">
   window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
   window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
<script>
$("#testForm").submit(function (e) {
    e.preventDefault();
    var data = [];
    data["test"] = "test";
    data[csrfTokenName] = csrfTokenValue;
    $.post('/', data, function(response) {
        console.log(response);
    });
});
</script>

The console keeps logging "400 Bad Request". What am I doing wrong ?

1

You need to define a route via action param otherwise Craft has no idea where to route the request. Your data variable only only contains

data = [
    'test' => 'test',
    TOKEN_NAME => TOKEN_VALUE
]

and nothing else

You need to include action => plugin-handle/controller-id/function-name

You can see a working example at basic ajax how to

| 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.