]> BookStack Code Mirror - bookstack/blob - resources/js/components/ajax-form.js
Finished breakdown of attachment vue into components
[bookstack] / resources / js / components / ajax-form.js
1 import {onEnterPress, onSelect} from "../services/dom";
2
3 /**
4  * Ajax Form
5  * Will handle button clicks or input enter press events and submit
6  * the data over ajax. Will always expect a partial HTML view to be returned.
7  * Fires an 'ajax-form-success' event when submitted successfully.
8  * @extends {Component}
9  */
10 class AjaxForm {
11     setup() {
12         this.container = this.$el;
13         this.url = this.$opts.url;
14         this.method = this.$opts.method || 'post';
15         this.successMessage = this.$opts.successMessage;
16         this.submitButtons = this.$manyRefs.submit || [];
17
18         this.setupListeners();
19     }
20
21     setupListeners() {
22         onEnterPress(this.container, event => {
23             this.submit();
24             event.preventDefault();
25         });
26
27         this.submitButtons.forEach(button => onSelect(button, this.submit.bind(this)));
28     }
29
30     async submit() {
31         const fd = new FormData();
32         const inputs = this.container.querySelectorAll(`[name]`);
33         console.log(inputs);
34         for (const input of inputs) {
35             fd.append(input.getAttribute('name'), input.value);
36         }
37
38         this.container.style.opacity = '0.7';
39         this.container.style.pointerEvents = 'none';
40         try {
41             const resp = await window.$http[this.method.toLowerCase()](this.url, fd);
42             this.container.innerHTML = resp.data;
43             this.$emit('success', {formData: fd});
44             if (this.successMessage) {
45                 window.$events.emit('success', this.successMessage);
46             }
47         } catch (err) {
48             this.container.innerHTML = err.data;
49         }
50
51         window.components.init(this.container);
52         this.container.style.opacity = null;
53         this.container.style.pointerEvents = null;
54     }
55
56 }
57
58 export default AjaxForm;