Can't send a submit fetch request

Viewed 79

I searched for a long time without results about this question. The problem is that when I try to send an asynchronous request to another web page I don't have any response. I think the problem is where the FormData takes its values but I don't know why... Here is the code:

const addBooking_form = document.getElementById("form_addResa");

addBooking_form.addEventListener("submit", (event) => {
    event.preventDefault();

    // Send asynchronous request to /api/booking/new
    const formData = new FormData(addBooking_form);
    const searchParams = new URLSearchParams(formData);

    console.log(formData);
    console.log(searchParams);
    const asyncReqAdd = fetch("api/booking/new", {
        method: "POST",
        body: formData
    });
    asyncReqAdd.then(response => {
        return console.log(response.text() == 'undefined' ? 'Fetch reponse <=> undefined' : response);
    }).then((response) => {
        console.log(response)
        table.innerHTML = response;
    });
    return console.log('New booking submited');
})

I know that the link and the form id are correct...

HTML FORM :

<form id="form_addResa">
        <div class="fieldset flexCol-around">
            <label for="input_lieu">Lieu *</label>
            <select id="input_lieu" name="place">
                <option value="none">&lt; Séléctionner un lieu &gt;</option>
                <option value="Salammbô">Salammbô</option>
                <option value="Pergola">Pergola</option>
                <option value="Salon Jaune">Salon Jaune</option>
                <option value="1001 Bougies">1001 bougies</option>
            </select>
            <div class="flexRow-around">
                <div class="flexCol-around">
                    <label for="input_date">Date *</label>
                    <input id="input_date" type="date" name="date">
                </div>
                <div class="flexCol-around">
                    <label for="input_time">Heure *</label>
                    <input id="input_time" type="time" name="time">
                </div>
            </div>
            <label for="input_nom">Nom *</label>
            <input id="input_nom" type="text" name="name">
            <label for="input_prenom">Prénom *</label>
            <input id="input_prenom" type="text" name="firstName">
        </div>
        <div class="fieldset flexCol-around">
            <label for="input_couverts">Nombre de couverts *</label>
            <input id="input_couverts" type="number" name="coverts">
            <label for="input_intExt">Client interne / externe *</label>
            <select name="intExt" id="input_intExt">
                <option value="ext">Externe</option>
                <option value="int">Interne</option>
            </select>
            <label for="input_contacte">Contacter le client *</label>
            <input id="input_contacte" type="text" placeholder="Numéro de chambre / téléphone / E-mail" name="contact">
        </div>
        <div class="fieldset">
            <textarea id="input_note" placeholder="Note :" name="notes"></textarea>
        </div>
        <div class="flexRow-around">
            <input type="reset" value="Annuler" style="background: white;">
            <input type="submit" onclick="unselectBooking();">
        </div>
    </form>

Can you give me a solution for this?

1 Answers

You could use async/await with a try catch block to see what goes wrong.

Something like this (pseudo):

addBooking_form.addEventListener("submit", async (event) => {
    event.preventDefault();
    const { date, time, name, place } = Object.fromEntries(new FormData(event.target))

    try {
      const respone = await fetch("api/booking/new", {
        method: "POST",
        body: { date, time, name, place }
      });
      const data = await response.json()
      // do something with data
      console.log(data)
    } catch(e) {
      // do some error handling
      console.log('error', e)
    }
})

Update: you can use Object.formEntries on FormData to get the values of your named input fields and then pass them to the body. This way, you should have valid JSON data.

I also removed the element selector since you already got the element via event

Related