Testing Form

<!-- Paste this into a WordPress "Custom HTML" block -->
<div id="ldas-form-wrapper">
  <form id="ldas-interaction-form" action="/wp-admin/admin-ajax.php" method="POST">
    <p>
      <label for="ldas-name">Name</label><br>
      <input type="text" id="ldas-name" name="name" required style="width:100%;padding:0.5em;border:1px solid #ccc;border-radius:4px;">
    </p>
    <p>
      <label for="ldas-email">Email</label><br>
      <input type="email" id="ldas-email" name="email" required style="width:100%;padding:0.5em;border:1px solid #ccc;border-radius:4px;">
    </p>
    <p>
      <label for="ldas-message">Message</label><br>
      <textarea id="ldas-message" name="message" required style="width:100%;padding:0.5em;border:1px solid #ccc;border-radius:4px;" rows="4"></textarea>
    </p>
    <input type="hidden" name="action" value="ldas_interaction_form">
    <input type="hidden" id="ldas-nonce" name="nonce" value="<?php echo wp_create_nonce('ldas_interaction_form'); ?>">
    <p><button type="submit" style="padding:0.5em 1em;border:none;border-radius:4px;background:#0073aa;color:#fff;cursor:pointer;">Send</button></p>
  </form>
  <div id="ldas-form-response" style="margin-top:1em;"></div>
</div>

<script>
(function(){
  document.addEventListener('DOMContentLoaded', function(){
    var form = document.getElementById('ldas-interaction-form');
    form.addEventListener('submit', function(e){
      e.preventDefault();
      var data = new FormData(form);
      fetch(form.action, {
        method: 'POST',
        credentials: 'same-origin',
        body: data
      }).then(function(r){ return r.json(); })
        .then(function(response){
          var resp = document.getElementById('ldas-form-response');
          if(response.success){
            resp.innerHTML = '<p style="color:green;">'+response.data+'</p>';
            form.reset();
          } else {
            resp.innerHTML = '<p style="color:red;">'+response.data+'</p>';
          }
        }).catch(function(){
          document.getElementById('ldas-form-response').innerHTML = '<p style="color:red;">Error submitting form.</p>';
        });
    });
  });
})();
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *