Send form data by e-mail

Asked

Viewed 157 times

2

I downloaded the codes from a page on https://html5up.net/ to use as a temporary page while the site of an event I organize is not ready. The page has only one field where the person puts the email and click send.

I need that when she clicks the button Send, the email that she typed is sent to me via email so I can register it.

In the head of HTML there’s a line lynching the index.html to page with the JS (down the line):

head of index.html

<link rel="stylesheet" href="assets/css/main.css" />

index.html

<!-- Signup Form -->
<form id="signup-form" method="post" action="#">
   <input type="email" name="email" id="email" placeholder="E-mail" />
   <input type="submit" value="Enviar" />
</form>

main.js

// Signup Form.

(function() {

   // Vars.
   var $form = document.querySelectorAll('#signup-form')[0],
   $submit = document.querySelectorAll('#signup-form input[type="submit"]')[0],
   $message;

   // Bail if addEventListener isn't supported.
   if (!('addEventListener' in $form))
   return;

   // Message.
   $message = document.createElement('span');
   $message.classList.add('message');
   $form.appendChild($message);

   $message._show = function(type, text) {

      $message.innerHTML = text;
      $message.classList.add(type);
      $message.classList.add('visible');

      window.setTimeout(function() {
         $message._hide();
      }, 3000);
   };

   $message._hide = function() {
      $message.classList.remove('visible');
   };

   // Events.
   // Note: If you're *not* using AJAX, get rid of this event listener.
   $form.addEventListener('submit', function(event) {

      event.stopPropagation();
      event.preventDefault();

      // Hide message.
      $message._hide();

      // Disable submit.
      $submit.disabled = true;

      // Process form.
      // Note: Doesn't actually do anything yet (other than report back with a "thank you"),
      // but there's enough here to piece together a working AJAX submission call that does.
      window.setTimeout(function() {

         // Reset form.
         $form.reset();

         // Enable submit.
         $submit.disabled = false;

         // Show message.
         $message._show('success', 'Obrigado! Nos vemos em breve ; )');
         //$message._show('failure', 'Something went wrong. Please try again.');

      }, 750);

   });

})();
  • If your server supports PHP you can use Phpmailer https://answall.com/questions/251300/formul%C3%A1rio-html-e-php/251473#251473

  • Do you just want the email to sign up for an email marketing? If it is, just use the code directly from the platform. Tell us what you really need to send the code ready, or give us a more graphic solution possible.

  • @Genesisr. I only need to receive the e-mail to register on the Mkt email platform yes, only I didn’t want to lose the layout of the site. When someone clicks to send a "thank you" message appears, for example. I want it to stay.

  • Which server language you use, php?

  • @Private Yes, it’s php!

2 answers

0

I believe that there is no way to send e-mail via Javascript, since it is a language client-side, because anyone could open the console from the browser and inject something into your code causing some kind of damage. You would have to use a language server-side together with the Javascript to make the shipments.

0


You can enter Ajax in this code, but you will need to create a PHP file that will receive the email sent by the form and that will send the email to be registered to your email. In the example below, I named the PHP file as enviar_email.php.

I have also made a small change to these lines:

var $form = document.querySelectorAll('#signup-form')[0],
$submit = document.querySelectorAll('#signup-form input[type="submit"]')[0],

To:

var $form = document.querySelector('#signup-form'),
$submit = document.querySelector('#signup-form input[type="submit"]'),

Since there is only one form on the page, it is not necessary to use querySelectorAll.

Another suggestion is to put required="required" in the field email, for the HTML itself to validate the field, otherwise the form will be submitted empty or with an invalid email:

<input required="required" type="email" name="email" id="email" placeholder="E-mail" />

Let’s get down to business:

In the PHP file you can create a sending code with the function mail() of PHP:

PHP:

<?php
$email = $_GET['email']; // recebe o campo do formulário

if(isset($email)){ // verifica se o valor foi recebido
   $corpo = '
   <html>
   <head>
   </head>
   <body>
   Email: '.$email.'
   </body>
   </html>
   '; 

   $headers = "MIME-Version: 1.1\n";
   $headers .= "Content-type: text/html; charset=iso-8859-1\n";
   $headers .= "From: [email protected]\n";
   $headers .= "Return-Path: [email protected]\n";
   $envio = mail("[email protected]", "Novo email enviado pelo site", $corpo, $headers);
   if($envio){
     echo 'email enviado'; // envio a confirmação pro Ajax
   }
}
?>

Obs.: the email in From usually should be an email from the domain itself, or the provider will block sending. The settings of the $headers may vary from server to server.

In your code, I entered an Ajax that will call the enviar_email.php. If you use another name, you need to change in Ajax as well.

Your complete code will look like this:

HTML + Javascript:

<form id="signup-form" method="post" action="#">
   <input required="required" type="email" name="email" id="email" placeholder="E-mail" />
   <input type="submit" value="Enviar" />
</form>

<script>
(function() {

   // Vars.
   var $form = document.querySelector('#signup-form'),
   $submit = document.querySelector('#signup-form input[type="submit"]'),
   $message;

   // Bail if addEventListener isn't supported.
   if (!('addEventListener' in $form))
   return;

   // Message.
   $message = document.createElement('span');
   $message.classList.add('message');
   $form.appendChild($message);

   $message._show = function(type, text) {

      $message.innerHTML = text;
      $message.classList.add(type);
      $message.classList.add('visible');

      window.setTimeout(function() {
         $message._hide();
      }, 3000);
   };

   $message._hide = function() {
      $message.classList.remove('visible');
   };

   // Events.
   // Note: If you're *not* using AJAX, get rid of this event listener.
   $form.addEventListener('submit', function(event) {

      event.stopPropagation();
      event.preventDefault();

      // Hide message.
      $message._hide();

      // Disable submit.
      $submit.disabled = true;

      var $email = document.querySelector("#email").value;

      //// INÍCIO DO AJAX

      var http = false;
      http = new XMLHttpRequest();
      var url_="http://marcos.lfels.xyz/__testes/erec/assets/js/enviar_email.php?email="+$email;
      http.open("POST",url_,true);
      http.onreadystatechange=function(){

          if(http.readyState==4){
            if(http.responseText.indexOf('email enviado') != -1){
               $message._show('success', 'Obrigado! Nos vemos em breve! ;)');
            }else{
               $message._show('failure', 'Something went wrong. Please try again.');
            }
          }

         // Reset form.
         $form.reset();

         // Enable submit.
         $submit.disabled = false;

      }
      http.send(null);

      //// FIM DO AJAX

   });

})();
</script>
  • OK, worked. I am receiving the registered emails!!! Thank you! The message is also correct: "Thank you! See you soon! ;)", but now it’s showing up with the css settings of the error message, with red font and the bug face. Until then, even without sending the data, when we learned to send, appeared the message of success...

  • @Marcoslichtenfels There was a little problem there in Ajax, I thought it would work but it can’t. You have to do 2 if. I’ve already updated the answer, where you have if(http.readyState==4){... just change your code, it’s only a few lines, about 7...

  • It worked perfectly! Super Thank You, @.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.