Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Refactor async forms' code

dominik-zeglena1cac58d560b
diff --git a/saleor/static/dashboard/js/components/async-form.js b/saleor/static/dashboard/js/components/async-form.js
index 26d94a9338..12e6efd93f 100644
--- a/saleor/static/dashboard/js/components/async-form.js
+++ b/saleor/static/dashboard/js/components/async-form.js
@@ -1,28 +1,42 @@
-import {initSelects} from './utils';
+import { initSelects } from './utils';
-export default $(document).on('submit', '.form-async', function (e) {
- let that = this;
- $.ajax({
- url: $(that).attr('action'),
- method: 'post',
- data: $(that).serialize(),
- complete: function (response) {
- if (response.status === 400) {
- $(that).parent().html(response.responseText);
- initSelects();
- } else {
- $('.modal-close').click();
- }
+const onAsyncFormSubmit = (e) => {
+ e.preventDefault();
+ const $target = $(e.currentTarget);
+ fetch($target.attr('action'), {
+ method: 'POST',
+ body: new FormData($target[0]),
+ credentials: 'same-origin',
+ headers: {
+ 'X-CSRFToken': $.cookie('csrftoken'),
},
- success: function (response) {
- if (response.redirectUrl) {
- window.location.href = response.redirectUrl;
- } else {
- location.reload();
- }
+ }).then((res) => {
+ let output;
+ if (res.status !== 200) {
+ output = new Error(res.statusText);
+ } else {
+ output = res.text();
+ }
+ return output;
+ }).then((data) => {
+ if (data.redirectUrl) {
+ window.location.href = data.redirectUrl;
+ } else {
+ window.location.reload();
}
+ }).catch((err) => {
+ $target.parent().html(err);
+ initSelects();
});
- e.preventDefault();
-}).on('click', '.modal-close', function () {
- $('.modal').modal('close');
-});
+};
+
+const onModalClose = () => $('.modal').modal('close');
+
+function init() {
+ return $(document).on('submit', '.form-async', onAsyncFormSubmit)
+ .on('click', '.modal-close', onModalClose);
+}
+
+export {
+ init as default,
+};