云致官网

validate.js 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * PHP Email Form Validation - v3.2
  3. * URL: https://bootstrapmade.com/php-email-form/
  4. * Author: BootstrapMade.com
  5. */
  6. (function () {
  7. "use strict";
  8. let forms = document.querySelectorAll('.php-email-form');
  9. forms.forEach( function(e) {
  10. e.addEventListener('submit', function(event) {
  11. event.preventDefault();
  12. let thisForm = this;
  13. let action = thisForm.getAttribute('action');
  14. let recaptcha = thisForm.getAttribute('data-recaptcha-site-key');
  15. if( ! action ) {
  16. displayError(thisForm, 'The form action property is not set!')
  17. return;
  18. }
  19. thisForm.querySelector('.loading').classList.add('d-block');
  20. thisForm.querySelector('.error-message').classList.remove('d-block');
  21. thisForm.querySelector('.sent-message').classList.remove('d-block');
  22. let formData = new FormData( thisForm );
  23. if ( recaptcha ) {
  24. if(typeof grecaptcha !== "undefined" ) {
  25. grecaptcha.ready(function() {
  26. try {
  27. grecaptcha.execute(recaptcha, {action: 'php_email_form_submit'})
  28. .then(token => {
  29. formData.set('recaptcha-response', token);
  30. php_email_form_submit(thisForm, action, formData);
  31. })
  32. } catch(error) {
  33. displayError(thisForm, error)
  34. }
  35. });
  36. } else {
  37. displayError(thisForm, 'The reCaptcha javascript API url is not loaded!')
  38. }
  39. } else {
  40. php_email_form_submit(thisForm, action, formData);
  41. }
  42. });
  43. });
  44. function php_email_form_submit(thisForm, action, formData) {
  45. fetch(action, {
  46. method: 'POST',
  47. body: formData,
  48. headers: {'X-Requested-With': 'XMLHttpRequest'}
  49. })
  50. .then(response => {
  51. if( response.ok ) {
  52. return response.text()
  53. } else {
  54. throw new Error(`${response.status} ${response.statusText} ${response.url}`);
  55. }
  56. })
  57. .then(data => {
  58. thisForm.querySelector('.loading').classList.remove('d-block');
  59. if (data.trim() == 'OK') {
  60. thisForm.querySelector('.sent-message').classList.add('d-block');
  61. thisForm.reset();
  62. } else {
  63. throw new Error(data ? data : 'Form submission failed and no error message returned from: ' + action);
  64. }
  65. })
  66. .catch((error) => {
  67. displayError(thisForm, error);
  68. });
  69. }
  70. function displayError(thisForm, error) {
  71. thisForm.querySelector('.loading').classList.remove('d-block');
  72. thisForm.querySelector('.error-message').innerHTML = error;
  73. thisForm.querySelector('.error-message').classList.add('d-block');
  74. }
  75. })();