I have quite a simple registration form, something like this:
<script type="text/javascript">
window.csrfTokenName = "{{ craft.config.get('csrfTokenName') }}";
window.csrfTokenValue = "{{ craft.request.getCsrfToken }}";
</script>
<form id="registerUser" method="post" accept-charset="UTF-8" class="flex-stack" novalidate @submit.prevent="userFormValidation()">
<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="redirect" value="user/registration-success">
<label for="username">{{ "Username (no spaces)"|t }} <em>*</em></label>
<input id="username" type="text" name="username" v-model.lazy.trim="user.userDetails.userName" :class="{ 'error-field': usernameHasError }" required>
</form>
It gets passed to VueJS (which works). There I have the default code I find in every AJAX post on Craft StackExchange:
var data = $('#registerUser').serializeArray();
//--- Add CSRF token to data
data[window.csrfTokenName] = window.csrfTokenValue;
$.ajax({
type: "POST",
data: data,
url: "",
success: function(data, response){
console.log("success", response, data);
},
error: function(response) {
console.log("error", response);
}
});
This works when the CSRF is disabled in the config, but when enabled, I always get a bad request, CSRF token invalid error.
What am I doing wrong here? There's no Craft caching going on.
serializeArray
won't produce data in a way Craft CMS will proceed it. It's not a good idea to do that. Besides that why don't you include the token in your form from the beginning? Because this is never the default code you can find in every ajax request – Robin Schambach Aug 23 '18 at 17:06