Подтверждающее сообщение не отображается в контактной форме javascript - PullRequest
0 голосов
/ 10 ноября 2019

Я использовал emailJS.com для создания контактной формы. Форма работает с кодом ниже:

<script type="text/javascript">

  window.onload = function () {
    document.getElementById('contact-form').addEventListener('submit', function (event) {
      event.preventDefault();
      emailjs.sendForm('gmail2', 'filtrastop', this);
      document.getElementById('contact-form').reset();
    });

    document.getElementById('form2').addEventListener('submit', function (event) {
      event.preventDefault();
      emailjs.sendForm('gmail2', 'filtrastop', this);
      document.getElementById('form2').reset();
    });
  }

</script>

Я пытаюсь добавить подтверждение / сообщение об ошибке , которое отображается пользователю при отправке формы. После прочтения документов (https://www.emailjs.com/docs/sdk/send-form/)

Мой код теперь выглядит так, но я не вижу никаких сообщений? Пожалуйста, помогите!

<script type="text/javascript">

  window.onload = function () {
    document.getElementById('contact-form').addEventListener('submit', function (event) {
      event.preventDefault();
      emailjs.sendForm('gmail2', 'filtrastop', this).then(function (response) {
        console.log('SUCCESS!', response.status, response.text);
      }, function (error) {
        console.log('FAILED...', error);
      });
      document.getElementById('contact-form').reset();
    });

    document.getElementById('form2').addEventListener('submit', function (event) {
      console.log('SUCCESS!', response.status, response.text);
    }, function (error) {
      console.log('FAILED...', error);
    });
  }

</script>

Ответы [ 2 ]

2 голосов
/ 10 ноября 2019

Пожалуйста, проверьте вашу 'form2' addEventListener (). Без вызова emailjs.send () вашего непосредственно используемого объекта ответа вы получите неопределенную ошибку. Сначала вы можете использовать emailjs.send (), а затем использовать объект ответа. Пожалуйста, проверьте мой код.

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

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com@2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
    (function () {
        emailjs.init("YOUR_USER_ID");
    })();

    window.onload = function () {
        document.getElementById('contact-form').addEventListener('submit', function (event) {
            event.preventDefault();
            var templateParams = {
                to_name: 'prabhat',
                from_name: 'Tapas',
                message_html: 'Please Find out the attached file'
            };

            emailjs.send('serviceID', 'templateID', templateParams)
                .then(function (response) {
                    if (response.status == 200 && response.text == 'OK')
                        alert('Your message has been sent Successfully..!!!');
                    else
                        alert('Sorry there was a problem. Please try again...!!!');
                }, function (error) {
                    alert('Sorry there was a problem. Please try again...!!!');
                });
            document.getElementById('contact-form').reset();
        });

        document.getElementById('form2').addEventListener('submit', function (event) {
            event.preventDefault();
            var templateParams = {
                to_name: 'prabhat',
                from_name: 'Padhy',
                message_html: 'Please Find out the attached file'
            };

            emailjs.send('serviceID', 'templateID', templateParams)
                .then(function (response) {
                    if (response.status == 200 && response.text == 'OK')
                        alert('Your message has been sent Successfully..!!!');
                    else
                        alert('Sorry there was a problem. Please try again...!!!');
                }, function (error) {
                    alert('Sorry there was a problem. Please try again...!!!');
                });
            document.getElementById('form2').reset();
        });
    }
</script>


<form id="contact-form">
    <button type="submit">Click Me</button>
</form>
<form id="form2">
    <button type="submit">Click Me</button>
</form>
1 голос
/ 10 ноября 2019

Прабхат был очень полезен, проходя через чат. Нам удалось заставить его работать именно так, как требуется!

Ниже обновленная версия рабочего кода:

<script type="text/javascript">
(function(){
emailjs.init("user_##########");
})();
</script>
<script type="text/javascript">
window.onload = function () {
document.getElementById('contact-form').addEventListener('submit', function (event) {
event.preventDefault();
emailjs.sendForm('gmail2', 'filtrastop', this).then(function (response) {
if (response.status == 200 && response.text == 'OK')
alert('Your message has been sent Successfully..!!!');
else
alert('Sorry there was a problem. Please try again...!');
}, function (error) {
alert('Sorry there was a problem. Please try again...!!!');
});
document.getElementById('contact-form').reset();
});

document.getElementById('form2').addEventListener('submit', function(event) {
event.preventDefault();
emailjs.sendForm('gmail2', 'filtrastop', this).then(function (response) {
if (response.status == 200 && response.text == 'OK')
alert('Your message has been sent Successfully..!!!');
else
alert('Sorry there was a problem. Please try again...!');
}, function (error) {
alert('Sorry there was a problem. Please try again...!!!');
});
document.getElementById('contact-form').reset();
});
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...