Jake Vanderwerf
2025-10-20 e729f920139f0c65902be2d6b2c32466b08375e8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
 * Frontend JavaScript for the Form Block
 * Handles form validation and submission
 */
class FormBlock {
    constructor() {
        this.controller = new window.jvbForm();
 
        document.querySelectorAll('.jvb-form-block form').forEach(form => {
            this.controller.registerForm(form);
        });
 
        this.controller.subscribe((event, data) => {
            if (event === 'form-submit') {
                this.handleFormSubmission(data);
            }
        });
    }
 
    async handleFormSubmission(data) {
        let [
            formId,
            formConfig,
            formData
        ] = [
            data.formId,
            data.config,
            data.data
        ];
        let form = formConfig.element;
 
        let headers = {
            'X-WP-Nonce': jvbSettings.nonce,
            'Content-Type': 'application/json'
        };
 
        data['form_type'] = formId;
        data['form_id'] = form.id;
        let block = form.closest('.jvb-form-block');
        this.controller.showFormStatus(formId, 'uploading');
        try {
            const response = await fetch (`${jvbSettings.api}forms`,
                {
                    method: 'POST',
                    headers,
                    body: JSON.stringify(formData)
                });
            if (!response.ok) {
                this.controller.showFormStatus(formId, 'error');
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message|| `Request failed with status ${response.status}`);
            }
            this.controller.showFormStatus(formId, 'submitted');
 
            this.controller.showSummary(formId, '.jvb-form-block');
            this.controller.store.delete(formId);
 
        } catch (error) {
            throw error;
        }
    }
 
    updateUI(response, block) {
 
        let summary = window.getTemplate('formSummary');
        summary.querySelector('h2').textContent = 'Success!';
        console.log('Form Response: ', response);
        console.log(summary);
        for (let [key, value] of Object.entries(response)) {
            let item = summary.querySelector(`#${key}`);
            if (item) {
                let title = item.querySelector('h4');
                if (title.innerText.includes('%s')) {
                    title.innerHTML = title.replace('%s', '<b>'+value+'</b>');
                } else {
                    item.querySelector('div').innerHTML = value;
                }
            }
        }
        block.append(summary);
    }
}
 
document.addEventListener('DOMContentLoaded', function() {
    new FormBlock();
});