How to send info from form to my email on JS?

79 Views Asked by At

I need information from a form that someone filled out to be sent to my email when a button is clicked, using JS only, without PHP. My code:

<form action="form.js" method="post">
  <label for="name">Name</label><br>
  <input type="text" name="name" id="name" placeholder="Your name"><br>
  <label for="email">Email</label><br>
  <input type="email" name="email" id="email" placeholder="Your email"><br>
  <label for="password">Password</label><br>
  <input type="password" name="password" id="password" placeholder="Your password"><br>
  <label for="feedback">Feedback</label><br>
  <textarea name="feedback" id="" cols="30" rows="10" placeholder="Your feedback"></textarea><br>
  <button type="submit">Send</button>
</form>
<script src="./form.js"></script>

I try do it on php but my mentor say that I should do it only Js

Please help me how to do this <3

1

There are 1 best solutions below

2
iamdlm On

To send information from a form to your email using JavaScript only (without server-side scripting like PHP), you can use a service like EmailJS. Example:

<form id="contact-form">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <label for="message">Message:</label>
  <textarea id="message" name="message" required></textarea>

  <input type="submit" value="Send">
</form>

JavaScript:

<script src="https://cdn.emailjs.com/dist/email.min.js"></script>

emailjs.init("your_user_id");

document.getElementById("contact-form").addEventListener("submit", function (e) {
  e.preventDefault(); // Prevent the default form submission behavior

  // Get the form data
  const formData = new FormData(e.target);

  // Send the email
  emailjs.sendForm("your_service_id", "your_template_id", formData).then(
    function (response) {
      console.log("Email sent successfully", response);
      // You can add code here to show a success message or redirect the user
    },
    function (error) {
      console.error("Email sending failed", error);
      // You can add code here to show an error message
    }
  );
});