Untitled
public
Jul 27, 2024
Never
34
1 document.addEventListener('alpine:init', () => { 2 Alpine.data('formHandler', () => ({ 3 activeSection: 'events', 4 formData: { 5 firstname: '', 6 lastname: '', 7 email: '', 8 countryCode: '+46', 9 phone: '', 10 birthday: '', 11 gdprConsent: false 12 }, 13 csrfToken: '', 14 swiper: null, 15 init() { 16 // Fetch the CSRF token 17 this.csrfToken = document.querySelector('input[name="csrf_token"]').value; 18 console.log('Initializing swiper...'); 19 20 // Initialize Swiper 21 this.swiper = new Swiper('.swiper-container', { 22 direction: 'horizontal', 23 loop: false, 24 speed: 400, 25 spaceBetween: 0, 26 on: { 27 slideChange: () => { 28 const sections = ['events', 'register', 'about']; 29 this.activeSection = sections[this.swiper.activeIndex]; 30 console.log('Slide changed to:', this.activeSection); 31 } 32 } 33 }); 34 }, 35 goToSection(index) { 36 console.log('Navigating to section:', index); 37 this.swiper.slideTo(index); 38 }, 39 async validateAndSaveFormData() { 40 console.log('Starting form validation...'); 41 42 // Validation checks 43 if (this.formData.phone.startsWith('0')) { 44 alert('Phone number should not start with 0.'); 45 return; 46 } 47 48 if (!this.formData.gdprConsent) { 49 alert('You must consent to data processing to proceed.'); 50 return; 51 } 52 53 if (!this.isValidDate(this.formData.birthday)) { 54 alert('Invalid date format. Please use YYYY-MM-DD format.'); 55 return; 56 } 57 58 // Complete phone number 59 const completePhoneNumber = this.formData.countryCode + this.formData.phone; 60 this.formData.completePhoneNumber = completePhoneNumber; 61 62 console.log('Form data before sending:', JSON.stringify(this.formData)); 63 64 // Submit form data 65 try { 66 const response = await fetch('https://pnyx-0fe8297d9f8b.herokuapp.com/register', { 67 method: 'POST', 68 headers: { 69 'Content-Type': 'application/json', 70 'X-CSRFToken': this.csrfToken 71 }, 72 body: JSON.stringify(this.formData) 73 }); 74 75 const result = await response.json(); 76 console.log('Server response:', result); 77 78 if (response.ok) { 79 alert(result.message); 80 this.resetForm(); 81 window.location.href = '/'; 82 } else { 83 alert(result.message); 84 } 85 } catch (error) { 86 console.error('Error:', error); 87 alert('An error occurred. Please try again.'); 88 } 89 90 console.log('Form submission completed'); 91 }, 92 isValidDate(date) { 93 const regex = /^\d{4}-\d{2}-\d{2}$/; 94 if (!date.match(regex)) return false; 95 const [year, month, day] = date.split('-'); 96 if (year.length > 4 || month.length > 2 || day.length > 2) return false; 97 return true; 98 }, 99 resetForm() { 100 this.formData.firstname = ''; 101 this.formData.lastname = ''; 102 this.formData.email = ''; 103 this.formData.countryCode = '+46'; 104 this.formData.phone = ''; 105 this.formData.birthday = ''; 106 this.formData.gdprConsent = false; 107 } 108 })); 109 console.log('Alpine initialized'); 110 });