skip to Main Content

When I submit a form that displays fetched data (display, download form) page does not refresh but if I submit a form that adds a new user or updates his data page refreshes. display, download form changes the HTML (displays data), the script is linked with defer attribute
every form shouldn’t refresh.

Forms:

<div class="content active">
            <form data-form-type="add">
              <input type="text" name="name" placeholder="Imie" />
              <input type="email" name="email" placeholder="E-mail" />
              <input
                type="text"
                name="status"
                placeholder="Status subskrypcji"
              />
              <button type="submit">Dodaj</button>
            </form>
          </div>
          <div class="content">
            <form data-form-type="display">
              <button type="submit">Wyświetl</button>
              <ul id="users"></ul>
            </form>
          </div>
          <div class="content">
            <form data-form-type="update">
              <input type="text" name="id" placeholder="ID klienta" />
              <input type="text" name="name" placeholder="Imię" />
              <input type="email" name="email" placeholder="E-mail" />
              <input
                type="text"
                name="status"
                placeholder="Status subskrypcji"
              />
              <button type="submit">Aktualizuj</button>
            </form>
          </div>
          <div class="content">
            <form data-form-type="delete">
              <input type="text" name="id" placeholder="ID klienta" />
              <button type="submit">Usuń</button>
            </form>
          </div>
          <div class="content">
            <form data-form-type="download">
              <button type="submit">Pobierz</button>
              <ul id="emails"></ul>
            </form>
          </div>

Js:

const forms = document.querySelectorAll("form");

forms.forEach((form) => {
  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    console.log("formualrz");
    debugger;
    const formType = form.dataset.formType || null;

    const formData = new FormData(form);

    formData.append("formType", formType);

    const response = await fetch(`http://localhost:3000/${formType}`, {
      method: "POST",
      body: formData,
    });

    try {
      console.log("formualrz");
      if (response.ok) {
        const responseData = await response.json();
        console.log(responseData);

        if (formType === "download") {
          const emailsBox = document.getElementById("emails");

          emailsBox.innerHTML = "";

          responseData.emails.forEach((email) => {
            const emailElement = document.createElement("li");
            emailElement.textContent = email;
            emailsBox.appendChild(emailElement);
          });
        } else if (formType === "display") {
          const usersBox = document.getElementById("users");

          usersBox.innerHTML = "";

          responseData.users.forEach((user) => {
            const userElement = document.createElement("li");
            let paragraph = document.createElement("p");

            paragraph.textContent = "ID: " + user.id;
            userElement.appendChild(paragraph);

            paragraph = document.createElement("p");

            paragraph.textContent = "Name: " + user.name;
            userElement.appendChild(paragraph);

            paragraph = document.createElement("p");

            paragraph.textContent = "Email: " + user.email;
            userElement.appendChild(paragraph);

            paragraph = document.createElement("p");

            paragraph.textContent = "Status: " + user.status;
            userElement.appendChild(paragraph);

            usersBox.appendChild(userElement);
          });
        } else if (formType === "update") {
          console.log("zakutalizowano");
        } else if (formType === "add") {
          console.log("dodano");
        }
      } else {
        console.error("Nie udało się wysłać danych");
      }
    } catch (error) {
      console.error("Błąd:", error);
    }
  });

  const submitButtons = form.querySelectorAll("button[type='submit']");
  submitButtons.forEach((button) => {
    button.addEventListener("click", async () => {
      const formType = form.dataset.formType || null;

      const formData = new FormData(form);

      formData.append("formType", formType);

      const response = await fetch(`http://localhost:3000/${formType}`, {
        method: "POST",
        body: formData,
      });

      try {
        console.log("formularz");
        if (response.ok) {
          const responseData = await response.json();
          console.log(responseData);

          if (formType === "download") {
            const emailsBox = document.getElementById("emails");

            emailsBox.innerHTML = "";

            responseData.emails.forEach((email) => {
              const emailElement = document.createElement("li");
              emailElement.textContent = email;
              emailsBox.appendChild(emailElement);
            });
          } else if (formType === "display") {
            const usersBox = document.getElementById("users");

            usersBox.innerHTML = "";

            responseData.users.forEach((user) => {
              const userElement = document.createElement("li");
              let paragraph = document.createElement("p");

              paragraph.textContent = "ID: " + user.id;
              userElement.appendChild(paragraph);

              paragraph = document.createElement("p");

              paragraph.textContent = "Name: " + user.name;
              userElement.appendChild(paragraph);

              paragraph = document.createElement("p");

              paragraph.textContent = "Email: " + user.email;
              userElement.appendChild(paragraph);

              paragraph = document.createElement("p");

              paragraph.textContent = "Status: " + user.status;
              userElement.appendChild(paragraph);

              usersBox.appendChild(userElement);
            });
          } else if (formType === "update") {
            console.log("zakutalizowano");
          } else if (formType === "add") {
            console.log("dodano");
          }
        } else {
          console.error("Nie udało się wysłać danych");
        }
      } catch (error) {
        console.error("Błąd:", error);
      }
    });
  });
});

I tried to use preventDefault but it doesn’t work properly.

2

Answers


  1. I think if you use Window: load event your problem might be solve

    window.addEventListener("load", (event) => {
      console.log("page is fully loaded");
      const forms = document.querySelectorAll("form");
    
     forms.forEach((form) => {
            form.addEventListener("submit", async (e) => {
            e.preventDefault();
            console.log("formualrz");
           ...
    });
    
    Login or Signup to reply.
  2. It is not easy to read your code; the code is repeating on both submit and click events (that is probably the main issue). And then all your code is nested — that is not easy to neither read or write!

    Here is a suggestion for some changes for a structure. The forms are fine, except that you complicate things by using dataset (data-*) when you can just give the form a name. And then don’t use "name" as a value for the name attributes in the input elements — use something else, like "username".

    So, in the following there is only one event listener for the submit event. The submit event can only come from a form and document will also know about each event, so the event listener is directly on document. To know witch form was submitted, use e.target.name. I made the fetch request, so that it has callback functions with then(), and in the last then() the callback function is creating a CustomEvent. That is handy now that different things need to happen afterwards. The name of the event changes according to the name of the form. And then you need event listeners for each event that can happen, like on_add, on_update, on_delete etc. The data from the response is stored ind the custom events detail property.

    For this demo I just request a random API with a GET request, but you can just replace it with the commented code.

    document.addEventListener('submit', e => {
      e.preventDefault();
      const formData = new FormData(e.target);
    
      //fetch(`http://localhost:3000/${e.target.name}`, {
      fetch('https://api.dictionaryapi.dev/api/v2/entries/en/hat', {
        //method: "POST", body: formData
        method: "GET"
      }).then(response => response.json()).then(json => {
        let event = new CustomEvent(`on_${e.target.name}`, {detail: json});
        document.dispatchEvent(event);
      });
    });
    
    document.addEventListener('on_add', e => {
      let responseData = e.detail;
      console.log('New user was added, response:', responseData);
      // do stuff
    });
    
    document.addEventListener('on_update', e => {
      let responseData = e.detail;
      console.log('An update was made, response:', responseData);
      // do stuff
    });
    <div class="content active">
      <form name="add">
        <input type="text" name="username" placeholder="Imie">
        <input type="email" name="email" placeholder="E-mail">
        <input type="text" name="status" placeholder="Status subskrypcji">
        <button type="submit">Dodaj</button>
      </form>
    </div>
    <div class="content">
      <form name="display">
        <button type="submit">Wyświetl</button>
        <ul id="users"></ul>
      </form>
    </div>
    <div class="content">
      <form name="update">
        <input type="text" name="id" placeholder="ID klienta" />
        <input type="text" name="username" placeholder="Imię" />
        <input type="email" name="email" placeholder="E-mail" />
        <input type="text" name="status" placeholder="Status subskrypcji" />
        <button type="submit">Aktualizuj</button>
      </form>
    </div>
    <div class="content">
      <form name="delete">
        <input type="text" name="id" placeholder="ID klienta" />
        <button type="submit">Usuń</button>
      </form>
    </div>
    <div class="content">
      <form name="download">
        <button type="submit">Pobierz</button>
        <ul id="emails"></ul>
      </form>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search