Components
9 months ago
autoloader.js
1 year ago
edit.js
6 months ago
ic-arrow-up-right-square.svg
11 months ago
index.js
6 months ago
reach-logo.svg
11 months ago
styles.scss
1 month ago
view.js
1 month ago
view.js
76 lines
| 1 | document.addEventListener('DOMContentLoaded', function() { |
| 2 | const translations = hostinger_reach_subscription_block_data.translations; |
| 3 | const formSelector = '.hostinger-reach-block-subscription-form'; |
| 4 | const forms = document.querySelectorAll(formSelector); |
| 5 | forms.forEach(form => { |
| 6 | const messageEl = form.querySelector('.reach-subscription-message'); |
| 7 | const iconElSuccess = form.querySelector('.reach-subscription-message__icon-success'); |
| 8 | const iconElError = form.querySelector('.reach-subscription-message__icon-error'); |
| 9 | const textEl = form.querySelector('.reach-subscription-message__text'); |
| 10 | const fieldsEl = form.querySelector('.hostinger-reach-block-form-fields'); |
| 11 | form.addEventListener('submit', function(e) { |
| 12 | e.preventDefault(); |
| 13 | |
| 14 | const submitBtn = form.querySelector('button[type="submit"]'); |
| 15 | const formData = new FormData(form); |
| 16 | const data = {}; |
| 17 | |
| 18 | formData.forEach((value, key) => { |
| 19 | if (key.includes('.')) { |
| 20 | const [ mainKey, subkey ] = key.split('.'); |
| 21 | |
| 22 | if ( ! data[mainKey] ) { |
| 23 | data[mainKey] = {}; |
| 24 | } |
| 25 | |
| 26 | data[mainKey][subkey] = value; |
| 27 | } else { |
| 28 | data[key] = value; |
| 29 | } |
| 30 | }); |
| 31 | |
| 32 | submitBtn.disabled = true; |
| 33 | |
| 34 | fetch(hostinger_reach_subscription_block_data.endpoint, { |
| 35 | method: 'POST', |
| 36 | headers: { |
| 37 | 'Content-Type': 'application/json', |
| 38 | 'X-WP-Nonce': hostinger_reach_subscription_block_data.nonce, |
| 39 | }, |
| 40 | body: JSON.stringify(data) |
| 41 | }) |
| 42 | .then(async response => { |
| 43 | messageEl.style.display = 'flex'; |
| 44 | form.reset(); |
| 45 | |
| 46 | if (response.ok) { |
| 47 | textEl.textContent = translations.thanks; |
| 48 | messageEl.classList.add('is-success'); |
| 49 | fieldsEl.style.display = 'none'; |
| 50 | iconElSuccess.style.display = 'block'; |
| 51 | iconElError.style.display = 'none'; |
| 52 | |
| 53 | } else { |
| 54 | const data = await response.json(); |
| 55 | if ( data.errors ) { |
| 56 | textEl.textContent = data.errors; |
| 57 | messageEl.style.display = 'block'; |
| 58 | messageEl.classList.add('is-error'); |
| 59 | submitBtn.disabled = false; |
| 60 | iconElSuccess.style.display = 'none'; |
| 61 | iconElError.style.display = 'block'; |
| 62 | } else { |
| 63 | throw new Error(); |
| 64 | } |
| 65 | |
| 66 | } |
| 67 | }) |
| 68 | .catch(err => { |
| 69 | messageEl.textContent = translations.error; |
| 70 | messageEl.style.display = 'block'; |
| 71 | submitBtn.disabled = false; |
| 72 | }); |
| 73 | }); |
| 74 | }); |
| 75 | }); |
| 76 |