PageSourceSearch

https://www.flatworldsolutions.com/js/form-handler-script.js?v=21.1-05-2026

js flatworldsolutions.com collected 2026-09-24 17:47:13 UTC 12,424 bytes, 337 lines download raw bytes

1var restrictedDomains = ["@gmail.com", "@outlook.com", "@yahoo.com", "@hotmail.com", "@msn.com", "@live.com", "@rediffmail.com"];
2var partialDomains = ["@gmai", "@outl", "@yaho", "@hotm", "@@msn.com", "@live.com", "@rediff"];
3
4document.addEventListener("DOMContentLoaded", function () {
5  let actionUrl = "/forms/contact-us-submit.php";
6  let forms = document.querySelectorAll(".main-form, .small-form");
7  if (forms.length === 0) {
8    //forms = document.querySelectorAll("form");
9  }
10  if (forms.length > 0) {
11    // Create and style the overlay element
12    const overlay = document.createElement("div");
13    overlay.id = "loadingOverlay";
14    Object.assign(overlay.style, {
15      display: "none", // Hidden by default
16      position: "fixed",
17      top: "0",
18      left: "0",
19      width: "100%",
20      height: "100%",
21      backgroundColor: "rgba(0, 0, 0, 0.5)", // Semi-transparent black
22      zIndex: "9999",
23      textAlign: "center",
24    });
25    // Create and style the loader element
26    const loader = document.createElement("div");
27    loader.className = "loader";
28    Object.assign(loader.style, {
29      position: "absolute",
30      top: "40%",
31      left: "50%",
32      transform: "translate(-50%, -50%)",
33      border: "8px solid #f3f3f3", // Light grey
34      borderTop: "8px solid #3498db", // Blue
35      borderRadius: "50%",
36      width: "60px",
37      height: "60px",
38      animation: "spin 1s linear infinite",
39    });
40    // Create the loading message element
41    const loadingMessage = document.createElement("div");
42    loadingMessage.innerText = "Processing, please wait...";
43    Object.assign(loadingMessage.style, {
44      position: "absolute",
45      top: "50%", // Position below the loader
46      left: "50%",
47      transform: "translate(-50%, -50%)",
48      color: "white",
49      fontSize: "20px",
50      marginTop: "10px", // Space between loader and message
51    });
52    // Create keyframe animation via JavaScript
53    const styleSheet = document.createElement("style");
54    styleSheet.type = "text/css";
55    styleSheet.innerText = `
56      @keyframes spin {
57          0% { transform: translate(-50%, -50%) rotate(0deg); }
58          100% { transform: translate(-50%, -50%) rotate(360deg); }
59      }
60  `;
61    document.head.appendChild(styleSheet);
62    // Append loader and message to the overlay
63    overlay.appendChild(loader);
64    overlay.appendChild(loadingMessage);
65    // Append the overlay to the body
66    document.body.appendChild(overlay);
67    forms.forEach(function (form) {
68      // console.log("Form found:", form);
69      // Capture the action URL from the form and then remove the action attribute
70      actionUrl = actionUrl ? actionUrl : form.getAttribute("action");
71      form.removeAttribute("action"); // Remove the action attribute for security
72      form.removeAttribute("onsubmit"); // Remove the onsubmit attribute for security
73      // Add novalidate attribute to disable HTML5 validation
74      form.setAttribute("novalidate", true);
75      // Dynamically create error elements
76      addErrorFields(form);
77      form.addEventListener("submit", function (event) {
78
79        //   console.log("Form submit event triggered");
80        event.preventDefault(); // Prevent the default form submission
81        // Create a hidden input field with the current page URL
82        const hiddenInput = document.createElement("input");
83        hiddenInput.type = "hidden";
84        hiddenInput.name = "currentpage_url";
85        //hiddenInput.value = window.location.href; // Get the full URL of the current page
86        hiddenInput.value = document.getElementById("url_with_parameters").value; // Get the full URL of the current page
87        form.appendChild(hiddenInput);
88        const formData = new FormData(form);
89        // Debug: log all hidden inputs inside this form at submit time
90        var hiddenInputs = form.querySelectorAll('input[type="hidden"]');
91        var hiddenMap = {};
92        hiddenInputs.forEach(function(inp) { hiddenMap[inp.name] = inp.value; });
93        console.log('[FormSubmit] Total inputs in form:', form.querySelectorAll('input').length);
94        console.log('[FormSubmit] Hidden inputs in form:', hiddenInputs.length, hiddenMap);
95        console.log('[FormSubmit] FormData UTM check:', {
96          utm_source: formData.get('utm_source'),
97          utm_medium: formData.get('utm_medium'),
98          userId: formData.get('userId'),
99          startedUrl: formData.get('startedUrl')
100        });
101        // Show the overlay with loader and message
102        overlay.style.display = "block";
103        // Client-side validation
104        const clientErrors = validateFormData(formData);
105        if (Object.keys(clientErrors).length > 0) {
106          displayValidationErrors(form, clientErrors);
107          overlay.style.display = "none"; // Hide overlay if validation fails
108          return; // Stop form submission if Client side Validation fails
109        }
110        // After Client side Validation
111        // Use AJAX to send form data for validation and processing
112        const xhr = new XMLHttpRequest();
113        xhr.open("POST", actionUrl, true); // Use captured action URL
114        xhr.onload = function () {
115          // Hide the overlay as soon as the request completes
116          overlay.style.display = "none";
117          if (xhr.status === 200) {
118            const response = JSON.parse(xhr.responseText);
119            if (response.isValid) {
120              if (formData.has("event-banner-form")) {
121                successPopup();
122                return false;
123              }
124              // Check if the form processing was successful
125              if (response.success) {
126                // Redirect to the success URL
127                localStorage.setItem('lead_submitted_from', window.location.href);
128                window.location.href = response.redirect_url;
129              } else {
130                // Redirect to the submission error URL
131                window.location.href = response.redirect_url;
132              }
133            } else {
134              displayValidationErrors(form, response.errors);
135            }
136          } else {
137            alert("There was an error processing your request.");
138          }
139        };
140        xhr.send(formData);
141      });
142    });
143  }
144});
145function addErrorFields(form) {
146  const fields = [
147    "FirstName",
148    "Email",
149    "phone",
150    "description",
151    "captcha_number",
152    "choose",
153    "budget",
154    "sf_Partner_Type",
155    "BranchName",
156    "OutsourcingConsider",
157    "service_name",
158  ];
159  fields.forEach(function (field) {
160    const inputField = form.querySelector(`[name=${field}]`);
161    if (inputField) {
162      let errorElement = document.createElement("span");
163      errorElement.className = `error ${field}-error`;
164      // Special handling for captcha_number to place error message correctly
165      if (field === "captcha_number") {
166        const captchaInput = form.querySelector('input[name="captcha_number"]');
167        if (captchaInput) {
168          const parentElement = captchaInput.parentElement;
169          parentElement.appendChild(errorElement);
170        }
171      } else if (field === "choose") {
172        const chooseGroup = form.querySelectorAll('input[name="choose"]');
173        if (chooseGroup.length > 0) {
174          const parentElement = chooseGroup[0].parentElement;
175          parentElement.appendChild(errorElement);
176        }
177      } else {
178        inputField.parentNode.insertBefore(
179          errorElement,
180          inputField.nextSibling
181        );
182      }
183    }
184  });
185}
186function validateFormData(formData) {
187  const errors = {};
188  // Validate FirstName
189  const firstName = formData.get("FirstName").trim();
190  if (!firstName || firstName.length < 4) {
191    errors.FirstName = "First name must be at least 4 characters long.";
192  }
193  // Validate Email
194  const email = formData.get("Email").trim();
195  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
196  if (!emailPattern.test(email)) {
197    errors.Email = "Please enter a valid email address.";
198  }
199
200  if (formData.has("event-banner-form")) {
201    var emailid = email.toLowerCase();
202    var personalEmail = restrictedDomains.some(domain => emailid.includes(domain)) || partialDomains.some(partial => emailid.includes(partial));
203    if (personalEmail) {
204      errors.Email = "Please enter a business email address.";
205    }
206  }
207  // Validate Phone
208  const phone = formData.get("phone").trim();
209  if (!/^[0-9]+$/.test(phone)) {
210    errors.phone = "Please enter a valid phone number.";
211  }
212  // Validate Description
213  if (formData.has("description")) {
214    const description = formData.get("description").trim();
215    if (!description) {
216      errors.description = "Description cannot be empty.";
217    } else if (description.length < 30) {
218      errors.description = "Description seems too short—please elaborate!";
219    }
220  }
221  // Validate Choose (radio buttons)
222  if (formData.has("choose")) {
223    const choose = formData.get("choose");
224    if (!choose) {
225      errors.choose = "Please Choose an option.";
226    }
227  }
228
229  // Validate Budget (select dropdown)
230  if (formData.has("budget")) {
231    const budget = formData.get("budget");
232    if (!budget || budget === "default") {
233      errors.budget = "Please select a budget.";
234    }
235  }
236
237  // Validate sf_Partner_Type (select dropdown)
238  if (formData.has("sf_Partner_Type")) {
239    const sfPartnerType = formData.get("sf_Partner_Type");
240    if (!sfPartnerType || sfPartnerType === "default") {
241      errors.sf_Partner_Type = "Please select a partner type.";
242    }
243  }
244  // Validate BranchName (text input)
245  if (formData.has("BranchName")) {
246    const branchName = formData.get("BranchName").trim();
247    if (!branchName) {
248      errors.BranchName = "Branch name cannot be empty.";
249    }
250  }
251  // Validate OutsourcingConsider (checkbox)
252  if (formData.has("OutsourcingConsider")) {
253    const outsourcingConsider = formData.get("OutsourcingConsider");
254    if (!outsourcingConsider) {
255      errors.OutsourcingConsider = "Please confirm your consideration.";
256    }
257  }
258
259  // Validate service_name (select dropdown)
260  if (formData.has("service_name")) {
261    const serviceName = formData.get("service_name");
262    if (!serviceName || serviceName === "default") {
263      errors.service_name = "Please select a service.";
264    }
265  }
266
267  return errors;
268}
269function displayValidationErrors(form, errors) {
270  // Clear previous errors
271  form.querySelectorAll(".error").forEach((e) => (e.textContent = ""));
272  for (const [key, message] of Object.entries(errors)) {
273    const errorSpan = form.querySelector(`.${key}-error`);
274    if (errorSpan) {
275      errorSpan.textContent = message;
276      errorSpan.style.display = "block";
277      errorSpan.style.marginBottom = "15px";
278      errorSpan.style.fontSize = "10px";
279      errorSpan.style.lineHeight = "15px";
280      errorSpan.style.color = "red"; // Optional: Style the error text
281      errorSpan.style.textAlign = "left"
282    }
283  }
284}
285
286
287function successPopup() {
288  // Create a popup element
289  const popupOverlay = document.createElement("div");
290  Object.assign(popupOverlay.style, {
291    position: "fixed",
292    top: "0",
293    left: "0",
294    width: "100%",
295    height: "100%",
296    backgroundColor: "rgba(0, 0, 0, 0.5)", // Semi-transparent black
297    zIndex: "10000",
298    display: "flex",
299    alignItems: "center",
300    justifyContent: "center",
301  });
302
303  const popup = document.createElement("div");
304  Object.assign(popup.style, {
305    backgroundColor: "#fff",
306    padding: "20px",
307    boxShadow: "0 4px 8px rgba(0, 0, 0, 0.2)",
308    borderRadius: "10px",
309    textAlign: "center",
310    width: "80%",
311    maxWidth: "500px",
312  });
313
314
315
316  // Add content to the popup
317  const utmAdgroup = document.querySelector('input[name="utm_adgroup"]')?.value;
318  popup.innerHTML = `
319                <h2 class="heading-red-color mx-lg-5 mb-2">Thank you for your interest!</h2>
320                <p class="sub-heading-para">
320Our Customer support team will contact you within 24 hours!</p>
321                <button id="closePopup" style="margin-top: 20px; padding: 10px 20px; background-color: #3498db; color: #fff; border: none; border-radius: 5px; cursor: pointer;">Close</button>
322            `;
323
324  // Append the popup to the overlay
325  popupOverlay.appendChild(popup);
326
327  // Append the overlay to the body
328  document.body.appendChild(popupOverlay);
329
330  closeEventModal();
331
332
333  // Add event listener to close the popup
334  document.getElementById("closePopup").addEventListener("click", () => {
335    popupOverlay.remove();
336  });
337}

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.