dwyl / learn-to-send-email-via-google-script-html-no-server

:email: An Example of using an HTML form (e.g: "Contact Us" on a website) to send Email without a Backend Server (using a Google Script) perfect for static websites that need to collect data.
GNU General Public License v2.0
3.15k stars 910 forks source link

reload upon submission #449

Closed daniice closed 1 year ago

daniice commented 1 year ago

Hello, Very helpful tutorial! I was wondering if there is a way to reload the form page upon submission, rather than showing a success message? Thanks in advance, Dani

cristianofromagio commented 1 year ago

You can use the window.location property to reload the page.

Replace around this part of form-submission-handler.js file:

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
-      form.reset();
-      var formElements = form.querySelector(".form-elements")
-      if (formElements) {
-        formElements.style.display = "none"; // hide form
-      }
-      var thankYouMessage = form.querySelector(".thankyou_message");
-      if (thankYouMessage) {
-        thankYouMessage.style.display = "block";
-      }
+      window.location.reload();
    }
  };

You can also replace it with window.location.assign("/other-page.html"); to redirect after submitting. See #156 for another example.

It is a good practice though, to provide users with some feedback for their actions, so they would know if something is working as they expected. You can try displaying the success message then reload/redirecting the page after some time. You can do that with a simple setTimeout:

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      form.reset();
      var formElements = form.querySelector(".form-elements")
      if (formElements) {
        formElements.style.display = "none"; // hide form
      }
      var thankYouMessage = form.querySelector(".thankyou_message");
      if (thankYouMessage) {
        thankYouMessage.style.display = "block";
      }
+      setTimeout(() => { window.location.reload(); }, 3500); // reloads the page after 3.5s
    }
  };
daniice commented 1 year ago

Thank you!! Will display and then reload :)