document.addEventListener("DOMContentLoaded", function () { // Find the form element by its ID var form = document.getElementById("form"); // Add event listener for form submission form.addEventListener("submit", function (event) { event.preventDefault(); // Prevent default form submission // Check if form validation passed if (form.checkValidity()) { // If form validation passed, call the API callApi(); } else { // If form validation failed console.error("Form validation failed"); } }); // Define the base URL for API endpoints var baseUrl; baseUrl = "https://pru-api-nprd.prudential.com.vn/pruforce/lead-corporate/uat2"; // Set the base URL based on the environment /*if (document.location.origin == "https://www.prudential.com.vn") { baseUrl = "https://pru-api-prod.prudential.com.vn/pruforce/lead-corporate/v1"; } else { baseUrl = "https://pru-api-nprd.prudential.com.vn/pruforce/lead-corporate/uat2"; } */ // Define specific endpoint URLs based on the environment var apiUrl = baseUrl + "/public/lead/corp-web"; // Function to call the API function callApi() { var formData = new FormData(form); var payload = { category: "XSELL_2024", firstName: formData .get("first-name") .trim() .split(" ") .slice(1) .join(" "), name: formData.get("first-name").trim().split(" ").slice(0, 1).join(" "), isCustomer: true, gender: null, mobile: formData.get("country-code") + formData.get("phone-no"), email: formData.get("email-address"), nationalId: null, provinceCode: formData.get("selectTopic"), timeContact: new Date().toISOString(), solutions: formData.get("enquirytype"), check: true, componentCode: window.location.href, messageCategory: null, messageDetails: null, j_captcha: null, utmCampaign: (new URLSearchParams(window.location.search)).get('utm_campaign') || "", utmMedium: (new URLSearchParams(window.location.search)).get('utm_medium') || "", utmSource: (new URLSearchParams(window.location.search)).get('utm_source') || "", }; fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), }) .then(function (response) { // Check the status code of the response if (response.ok) { // If the response status is in the range 200-299 return response.json(); // Parse JSON response } else { throw new Error( "[" + response.status + "] Có lỗi xảy ra, vui lòng thử lại sau" ); } }) .then(function (data) { // Handle API response data console.log("API response:", data); }) .catch(function (error) { // Handle errors console.error("Error:", error); alert(error); }); } });