简体   繁体   中英

How to add data to FormData and submit?

After passing the quiz, the user fills in the form with the fields: Name and Phone and sends the data to the mail. I have written code to submit a form. Now I need to make it so that when the form is submitted, the user's selected responses are also sent. The user's selected responses are stored in a userData object and

 //selected user responses const userData = { gender: "...", date: "...", month: "...", year: "...", allergy: "...", }; //submit form const form = document.getElementById("order_form"); form.addEventListener("submit", formSend); async function formSend(e) { e.preventDefault(); let error = formValidate(form); let formData = new FormData(form); if (error === 0) { let response = await fetch("sendmail.php", { method: "POST", body: formData, }); if (response.ok) { let result = await response.json(); form.reset(); } } } //sendmail.php //body if (trim(!empty($_POST['name']))) { $body .= '<p><strong>Имя:</strong>' . $_POST['name'] . '</p>'; } if (trim(!empty($_POST['phone']))) { $body .= '<p><strong>Телефон:</strong>' . $_POST['phone'] . '</p>'; }

You can use append method of FormData

formData.append('gender', userData.gender);
formData.append('date', userData.date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM