Как мне отправить информацию о моей форме при отправке на мой адрес электронной почты js? - PullRequest
0 голосов
/ 05 августа 2020

Я работаю над своим проектом, и у меня есть форма, в которой вы заполняете свое имя и адрес электронной почты, а затем нажимаете «Отправить». Все идет нормально. Проблема в том, что я пытаюсь, когда пользователь нажимает «отправить» информацию, которая была заполнена в форме (имя и адрес электронной почты) go, на мой личный адрес электронной почты. В настоящее время я использую электронную почту js, потому что она рекомендована моей школой, но она не работает, и я не понимаю, что делаю не так. Вот что я сделал до сих пор:

//I put this is the end of the <head> section

<script type="text/javascript" src="https://cdn.emailjs.com/sdk/2.2.4/email.min.js"></script>
    <script type="text/javascript">
        (function() {
            emailjs.init("user_"); //it has my user ID, just didn't want to share
        })();
</script>

//this is the form

<form id="testform" onsubmit="return sendMail(this);">
           <div class="box">
                 <label for="fullname" class="form-tag">Name</label>
                 <input type="text" name="name" id="fullname" class="form-control" required/>
                 <label for="emailaddress" class="form-tag">Email</label>
                 <input type="email" name="email" id="emailaddress" class="form-control" required/>
                 <div class="button">
                   <button id="submit" type="button" class="btn btn-light btn-lg">Submit</button>
                 </div>
            </div>
</form>

// и это прямо перед концом

<script src="assets/js/sendEmail.js"></script>

// sendEmail. js

function sendMail(contactForm) {
    emailjs.send("gmail", "yourjourney", {
        "from_name": contactForm.name.value,
        "from_email": contactForm.emailaddress.value,
    })
    .then(
        function(response) {
            console.log("SUCCESS", response);
        },
        function(error) {
            console.log("FAILED", error);
        }
    );
    return false;  // To block from loading a new page
}

Ответы [ 2 ]

1 голос
/ 05 августа 2020

, значит, в вашем коде есть две проблемы. Сначала ваша кнопка - это кнопка типа рядом с типом отправки. Во-вторых, вы используете return false, что означает, что вы останавливаете процесс отправки.

, чтобы вы могли заставить его работать без перезагрузки страницы, вам не нужно создавать форму. Это будет немного отличаться от того, чему вас учат в школе, но я надеюсь, что это поможет.

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/emailjs-com@2/dist/email.min.js'></script>
    <script type='text/javascript'>
        (function () {
            emailjs.init('user_ID');
        })();
    </script>
    <title>Document</title>
</head>
<body>
    <div class="box">
        <label for="fullname" class="form-tag">Name</label>
        <input type="text" name="name" id="fullname" class="form-control" required />
        <label for="emailaddress" class="form-tag">Email</label>
        <input type="email" name="email" id="emailaddress" class="form-control" required />
        <div class="button">
            <button id="button" type="button" class="btn btn-light btn-lg">Submit</button>
        </div>
    </div>

    <script src="assets/js/sendEmail.js"></script>
</body>
</html>

JS (sendEmail. js файл) :

//Getting the name and email from the DOM
let fullName = document.getElementById('fullname').value
let email = document.getElementById('emailaddress').value
//Getting the button from the DOM
let submitButton = document.getElementById('button') 

//Add event listener on click to the button - notice i added the event as argument to the function
submitButton.addEventListener('click', function(event){

    //prevent the reload of the page. here i prevent the event.
    event.preventDefault()

    //Sending the email with the name and email
    emailjs.send("gmail", "yourjourney", {
        "from_name": fullName,
        "from_email": email,
    })
        .then(
            function (response) {
                console.log("SUCCESS", response);
                
            },
            function (error) {
                console.log("FAILED", error);
                
            }

        );
})

Если вам нужна форма и ее часть для домашнего задания или что-то еще, дайте мне знать, чтобы я мог изменить код в соответствии с тем, что вы изучаете.

0 голосов
/ 05 августа 2020
//Getting the button from the DOM
let submitButton = document.getElementById('button') 

//Add event listener on click to the button - notice i added the event as argument to the function
submit.addEventListener('click', function(event){

    //prevent the reload of the page. here i prevent the event.
    event.preventDefault()

    //Getting the name and email from the DOM
    let fullName = document.getElementById('fullname').value
    let email = document.getElementById('emailaddress').value

    //Sending the email with the name and email
    emailjs.send("gmail", "yourjourney", {
        "from_name": fullName,
        "from_email": email,
    })
        .then(
            function (response) {
                console.log("SUCCESS", response);
                
            },
            function (error) {
                console.log("FAILED", error);
                
            }

        );
})
  1. Спасибо @elnatan vazana за помощь!
  2. Мой идентификатор пользователя был неверным, поэтому я изменил его, и теперь он работает нормально. Я могу получить информацию, отправленную в форму.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...