zzossig / hugo-theme-zzo

Make a blog with hugo zzo theme!
https://themes.gohugo.io//theme/hugo-theme-zzo/en/
MIT License
743 stars 256 forks source link

Enhancement for contact form #363

Open ohidurbappy opened 3 years ago

ohidurbappy commented 3 years ago

As you are using formspree, when a form is submitted it goes to https://formspree.io/ leaving our domain. We can make use of ajax feature provided by formspree. I have implemented it by hardcoding the form here : https://www.ohidur.com/contact/ you can send a test message to see how it works

Code

HTML


<form id="my-form" action="https://formspree.io/f/xyybngnp" method="POST" class="contact__form">
  <div class="contact__input--container">
    <div class="contact__input--wrapper">
      <label class="contact__label">
        Name    
      </label>
      <input type="text" name="name" class="contact__input" aria-label="Name">
    </div>
    <div class="contact__input--wrapper">
      <label class="contact__label">
        Email    
      </label>
      <input type="email" name="_replyto" class="contact__input" aria-label="Email">
    </div>
  </div>
  <div class="contact__message--wrapper">
    <label class="contact__label">
      Message    
    </label>
    <textarea name="message" class="contact__message" aria-label="Message"></textarea>
  </div>
<button id="my-form-button" class="contact__send" style="background-color:#a38e5d;color:#f1f1f1;">Submit</button>
<p id="my-form-status"></p>
</form>

Javascript


<script>
  window.addEventListener("DOMContentLoaded", function() {

    // get the form elements defined in your form HTML above

    var form = document.getElementById("my-form");
    var button = document.getElementById("my-form-button");
    var status = document.getElementById("my-form-status");

    // Success and Error functions for after the form is submitted

    function success() {
      form.reset();
      button.style = "display: none ";
      status.innerHTML = "Thanks!";
    }

    function error() {
      status.innerHTML = "Oops! There was a problem.";
    }

    // handle the form submission event

    form.addEventListener("submit", function(ev) {
      ev.preventDefault();
      var data = new FormData(form);
      ajax(form.method, form.action, data, success, error);
    });
  });

  // helper function for sending an AJAX request

  function ajax(method, url, data, success, error) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.setRequestHeader("Accept", "application/json");
    xhr.onreadystatechange = function() {
      if (xhr.readyState !== XMLHttpRequest.DONE) return;
      if (xhr.status === 200) {
        success(xhr.response, xhr.responseType);
      } else {
        error(xhr.status, xhr.response, xhr.responseType);
      }
    };
    xhr.send(data);
  }
</script>