PageSourceSearch

https://hrone.cloud/wp-content/themes/hrone-child/assets/js/popup-form-submit.js?ver=949022131

js hrone.cloud collected 2026-09-24 10:23:50 UTC 10,731 bytes, 229 lines download raw bytes

1/**
2 * Popup Form Submission Handler
3 * Submits form directly to HubSpot API (no AJAX/backend required)
4 */
5
6(function ($) {
7    'use strict';
8
9    /**
10     * Lightweight client-side sanitizers to avoid pushing unsafe/unexpected values
11     * into 3rd-party APIs. Server-side sanitization should still be enforced.
12     */
13    function sanitizePlainText(value, maxLen = 250) {
14        if (value === null || value === undefined) return '';
15        let str = String(value);
16        // Strip HTML tags
17        str = str.replace(/<[^>]*>/g, '');
18        // Remove ASCII control chars
19        str = str.replace(/[\u0000-\u001F\u007F]/g, '');
20        // Collapse whitespace
21        str = str.replace(/\s+/g, ' ').trim();
22        if (maxLen && str.length > maxLen) str = str.slice(0, maxLen);
23        return str;
24    }
25
26    function sanitizeEmail(value) {
27        // Keep it simple: trim, lower-case, remove spaces/control chars/tags.
28        const email = sanitizePlainText(value, 320).toLowerCase();
29        return email.replace(/\s+/g, '');
30    }
31
32    function sanitizePhoneIN(value) {
33        // Digits only, keep last 10 digits (common when country code is included)
34        const digits = String(value ?? '').replace(/\D/g, '');
35        return digits.length <= 10 ? digits : digits.slice(-10);
36    }
37
38    function sanitizeUrl(value) {
39        const raw = sanitizePlainText(value, 2000);
40        if (!raw) return '';
41        try {
42            const u = new URL(raw, window.location.origin);
43            // Only allow http/https URLs in payloads
44            if (u.protocol !== 'http:' && u.protocol !== 'https:') return '';
45            return u.href;
46        } catch (e) {
47            return '';
48        }
49    }
50
51    function sanitizePopupFormData(formData) {
52        const safe = { ...(formData || {}) };
53
54        safe.popup_name = sanitizePlainText(safe.popup_name, 120);
55        safe.popup_official_email = sanitizeEmail(safe.popup_official_email);
56        safe.popup_phone = sanitizePhoneIN(safe.popup_phone);
57        safe.city_popup = sanitizePlainText(safe.city_popup, 120);
58        safe.state_code = sanitizePlainText(safe.state_code, 50);
59        safe.popup_number_of_employee_v1 = sanitizePlainText(safe.popup_number_of_employee_v1, 50);
60
61        safe.utm_source = sanitizePlainText(safe.utm_source, 120);
62        safe.utm_medium = sanitizePlainText(safe.utm_medium, 120);
63        safe.utm_campaign = sanitizePlainText(safe.utm_campaign, 120);
64        safe.utm_content = sanitizePlainText(safe.utm_content, 120);
65        safe.utm_term = sanitizePlainText(safe.utm_term, 120);
66
67        safe.popup_permalink = sanitizeUrl(safe.popup_permalink);
68        safe.popup_page_title = sanitizePlainText(safe.popup_page_title, 200);
69
70        return safe;
71    }
72
73    // HubSpot API Configuration
74    const HUBSPOT_PORTAL_ID = '7277696';
75    const HUBSPOT_FORM_GUID = '6a8e8749-b385-4c50-b604-0a4564eeb452';
76    const HUBSPOT_API_URL = 'https://api.hsforms.com/submissions/v3/integration/submit/' + HUBSPOT_PORTAL_ID + '/' + HUBSPOT_FORM_GUID;
77
78    $(document).ready(function () {
79        // Popup Form Submit Handler
80        $("#popupFormSubmit").click(function (event) {
81            event.preventDefault();
82            var state = $('#input-box-city-popup').attr('data-state');
83            var isValid = true;
84            var email = $('#popup_official_email').val();
85
86            // Validate form fields
87            $(this).parent().find("input[type='text'], input[type='email']").each(function () {
88                if ($(this).val().trim() === '') {
89                    isValid = false;
90                    $(this).addClass('error');
91                } else {
92                    $(this).removeClass('error');
93                }
94
95                var phoneNum = $('#popup_phone_nu').val();
96                var phoneRegex = /^[6-9]\d{9}$/;
97                if (!phoneRegex.test(phoneNum)) {
98                    $('#popup_phone_nu').addClass('error');
99                    isValid = false;
100                } else {
101                    $('#popup_phone_nu').removeClass('error');
102                }
103            });
104
105            // Validate city
106            function validateCity() {
107                if (typeof inputBox_popup !== 'undefined' && typeof availableKeywords !== 'undefined') {
108                    const inputCity = inputBox_popup.value.trim();
109                    const cityExists = availableKeywords.some(({ city }) => city === inputCity);
110                    if (!cityExists) {
111                        $('.city-error-popup').html('City not found in the list. Please select a valid city.');
112                        return false;
113                    }
114                }
115                return true;
116            }
117
118            if (!validateCity()) {
119                isValid = false;
120                event.preventDefault();
121            }
122
123            if (!isValid) {
124                return false;
125            }
126
127            // Capture form data
128            const formData = captureFormData();
129            formData.state_code = state;
130            const sanitizedFormData = sanitizePopupFormData(formData);
131            const isEmpty = Object.values(sanitizedFormData).some(value => value !== '');
132
133            if (isEmpty) {
134                document.getElementById("popupFormSubmit").disabled = true;
135                document.getElementById("loaderpopup2").style.display = "block";
136
137                // Get HubSpot tracking cookie (hubspotutk) for API context
138                function getCookie(name) {
139                    const value = `; ${document.cookie}`;
140                    const parts = value.split(`; ${name}=`);
141                    if (parts.length === 2) return parts.pop().split(';').shift();
142                    return '';
143                }
144
145                const hubspotCookie = getCookie('hubspotutk') || '';
146
147                // Parse name into firstname and lastname
148                const name = sanitizedFormData.popup_name || '';
149                let firstname = '';
150                let lastname = '';
151                if (name) {
152                    const nameParts = name.trim().split(' ');
153                    firstname = nameParts[0] || '';
154                    lastname = nameParts.slice(1).join(' ') || '';
155                }
156
157                // Prepare data for HubSpot API
158                const hubspotData = {
159                    "submittedAt": new Date().toISOString(),
160                    "fields": [
161                        { "objectTypeId": "0-1", "name": "firstname", "value": firstname },
162                        { "objectTypeId": "0-1", "name": "lastname", "value": lastname },
163                        { "objectTypeId": "0-1", "name": "email", "value": sanitizedFormData.popup_official_email || '' },
164                        { "objectTypeId": "0-1", "name": "phone", "value": "+91" + (sanitizedFormData.popup_phone || '') },
165                        { "objectTypeId": "0-1", "name": "city", "value": sanitizedFormData.city_popup || '' },
166                        { "objectTypeId": "0-1", "name": "state_sap__cloned_", "value": state || '' },
167                        { "objectTypeId": "0-1", "name": "country", "value": "India" },
168                        { "objectTypeId": "0-1", "name": "number_of_employee_v1", "value": sanitizedFormData.popup_number_of_employee_v1 || '' },
169                        { "objectTypeId": "0-1", "name": "utm_source", "value": sanitizedFormData.utm_source || '' },
170                        { "objectTypeId": "0-1", "name": "utm_medium", "value": sanitizedFormData.utm_medium || '' },
171                        { "objectTypeId": "0-1", "name": "utm_campaign", "value": sanitizedFormData.utm_campaign || '' },
172                        { "objectTypeId": "0-1", "name": "utm_content", "value": sanitizedFormData.utm_content || '' },
173                        { "objectTypeId": "0-1", "name": "utm_term", "value": sanitizedFormData.utm_term || '' }
174                    ],
175                    "context": {
176                        "hutk": hubspotCookie,
177                        "pageUri": sanitizedFormData.popup_permalink || window.location.href,
178                        "pageName": sanitizedFormData.popup_page_title || document.title
179                    },
180                    "legalConsentOptions": {
181                        "consent": {
182                            "consentToProcess": true,
183                            "text": "I agree to allow HROne to store and process my personal data."
184                        }
185                    }
186                };
187
188                // Submit directly to HubSpot API (no AJAX/backend)
189                fetch(HUBSPOT_API_URL, {
190                    method: 'POST',
191                    headers: {
192                        'Content-Type': 'application/json'
193                    },
194                    body: JSON.stringify(hubspotData)
195                })
196                    .then(response => response.json())
197                    .then(data => {
198                        // Reset form and show success
199                        $('#popupForm')[0].reset();
200                        document.getElementById("popupFormSubmit").disabled = false;
201                        document.getElementById("loaderpopup2").style.display = "none";
202
203                        // Show success message
204                        if (data.inlineMessage) {
205                            $('.popupformresponse').html('<div class="hm-banner-msg"><div class="success-msg"> <h2>Success!</h2>' + data.inlineMessage + ' </div></div>');
206                        } else {
207                            $('.popupformresponse').html('<div class="hm-banner-msg"><div class="success-msg"> <h2>Success!</h2>Thank you for your submission!</div></div>');
208                        }
209
210                        // Redirect to thank you page
211                        setTimeout(function () {
212                            const thankYouUrl = (typeof hronePopupForm !== 'undefined' && hronePopupForm.thankYouUrl)
213                                ? hronePopupForm.thankYouUrl
214                                : window.location.origin + '/thankyou';
215                            window.location.href = thankYouUrl;
216                        }, 1000);
217                    })
218                    .catch(error => {
219                        console.error('Error submitting form:', error);
220                        document.getElementById("popupFormSubmit").disabled = false;
221                        document.getElementById("loaderpopup2").style.display = "none";
222                        $('.popupformresponse').html('<div class="hm-banner-msg"><div class="error-msg"> <h2>Error!</h2>There was an error submitting your form. Please try again.</div></div>');
223                    });
224            }
225        });
226    });
227
228})(jQuery);
229

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.