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>

and this is my js code:

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

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


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',

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

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.