From 4f1146dc334b0436126563520610bf260f1f1767 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=BCneyt=20=C5=9Eent=C3=BCrk?= Date: Fri, 5 Nov 2021 19:16:04 +0300 Subject: [PATCH] Added async submit function.. --- resources/assets/js/mixins/global.js | 5 ++++ resources/assets/js/plugins/form.js | 44 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/resources/assets/js/mixins/global.js b/resources/assets/js/mixins/global.js index 4bfc17773..5a82205d6 100644 --- a/resources/assets/js/mixins/global.js +++ b/resources/assets/js/mixins/global.js @@ -119,6 +119,11 @@ export default { this.form.submit(); }, + // Form Async Submit + async onAsyncSubmit() { + await this.form.asyncSubmit(); + }, + onHandleFileUpload(key, event) { this.form[key] = ''; this.form[key] = event.target.files[0]; diff --git a/resources/assets/js/plugins/form.js b/resources/assets/js/plugins/form.js index 1bf095e6b..c647cd875 100644 --- a/resources/assets/js/plugins/form.js +++ b/resources/assets/js/plugins/form.js @@ -409,6 +409,50 @@ export default class Form { .catch(this.onFail.bind(this)); } + async asyncSubmit() { + FormData.prototype.appendRecursive = function(data, wrapper = null) { + for (var name in data) { + if (name == "previewElement" || name == "previewTemplate") { + continue; + } + + if (wrapper) { + if ((typeof data[name] == 'object' || Array.isArray(data[name])) && ((data[name] instanceof File != true ) && (data[name] instanceof Blob != true))) { + this.appendRecursive(data[name], wrapper + '[' + name + ']'); + } else { + this.append(wrapper + '[' + name + ']', data[name]); + } + } else { + if ((typeof data[name] == 'object' || Array.isArray(data[name])) && ((data[name] instanceof File != true ) && (data[name] instanceof Blob != true))) { + this.appendRecursive(data[name], name); + } else { + this.append(name, data[name]); + } + } + } + }; + + this.loading = true; + + let data = this.data(); + + let form_data = new FormData(); + form_data.appendRecursive(data); + + await window.axios({ + method: this.method, + url: this.action, + data: form_data, + headers: { + 'X-CSRF-TOKEN': window.Laravel.csrfToken, + 'X-Requested-With': 'XMLHttpRequest', + 'Content-Type': 'multipart/form-data' + } + }) + .then(this.onSuccess.bind(this)) + .catch(this.onFail.bind(this)); + } + onSuccess(response) { this.errors.clear();