在单页网站上设置联系表单/脚本

时间:2022-12-05 07:40:10

Something I always seem to have difficulty with for some reason is setting up contact forms and the mail scripts and everything...this time for a single-paged website (my own portfolio) and thus requiring a dynamic solution without pages refreshes or external links ect. Something which I am not very experienced with.

由于某些原因,我似乎总是遇到困难的是设置联系表单和邮件脚本以及所有内容......这次是针对单页网站(我自己的投资组合),因此需要动态解决方案,无需刷新页面或外部链接等。我不太熟悉的东西。

My site is: http://www.samnorris.co.nz

我的网站是:http://www.samnorris.co.nz

I have been trying to learn from the website of http://www.alwayscreative.net and how they have theirs set up. The form uses a small jQuery plugin on GitHub called FormSentinel to handle the validation side of things - which seems to be working well enough, the submit button is disabled until the form is completed and it prompts for a correct e-mail address, the problem is that nothing happens when the submit/'Transmit' button is clicked.

我一直在尝试从http://www.alwayscreative.net的网站上学习,以及他们如何建立他们的网站。该表单在GitHub上使用一个名为FormSentinel的小jQuery插件来处理事物的验证方面 - 这似乎运行良好,提交按钮被禁用,直到表单完成并提示输入正确的电子邮件地址,问题是单击提交/'传输'按钮时没有任何反应。

This is presumably because I have not linked to any PHP script for actually processing the form, as I am unsure where it is actually called from in this scenario. I have a very basic mail.php on the root of my server - but from looking at the AlwaysCreative website the form action links back to the page itself and there is no reference to any PHP or mail scripts in the FormSentinel jquery (or documentation or anything for that matter...)

这可能是因为我没有链接到任何PHP脚本来实际处理表单,因为我不确定它在这种情况下实际调用的位置。我在我的服务器的根目录上有一个非常基本的mail.php - 但是从查看AlwaysCreative网站,表单操作链接回页面本身,并且没有引用FormSentinel jquery中的任何PHP或邮件脚本(或文档或任何事情......)

I'm just a bit confused (okay, a lot confused) as to how or where exactly to establish a link to a PHP processing script for the form without leading to any other external links/pages. With the FormSentinel plugin the page should fade out the form and load in a short "Thankyou" message in place of the containing fieldset but that's not happening either.

关于如何或在何处确切地建立表单的PHP处理脚本的链接而不导致任何其他外部链接/页面,我只是有点困惑(好吧,很多困惑)。使用FormSentinel插件,页面应该淡出表单并加载一个简短的“Thankyou”消息来代替包含字段集,但这也没有发生。

Javascript for the form:

表格的Javascript:

;(function($) {

  var formSentinel = {
    submitting: false,
    fields: [],
    rules: {
      required: /./,
      requiredNoWhitespace: /\S/,
      email: /\S/
    },
    init: function(form) {
      this.fields = form.elements;
      $('#submit-btn').removeClass('success').attr('disabled', 'disabled');
      for (var i = 0; i < this.fields.length; i++) {
        if ($(this.fields[i]).val() === '') {
          $(this.fields[i]).bind('focus', function() {
            formSentinel.statusListener(form);
          }); 
          $(this.fields[i]).bind('blur', function() {
            formSentinel.statusListener(form);
          });
        }
        $(this.fields[i]).bind('keydown, keyup', function() {
          var self = $(this);
          formSentinel.statusListener(form);
          if (self.hasClass('invalid') || self.hasClass('valid')) {
            self.bind('keydown', function() {
              formSentinel.fieldListener(this);
            });
          }
        });
      }
      $(form).submit(function () {
        if (formSentinel.submitting === false) {
          formSentinel.submitListener(this);
          $('html, body').animate({scrollTop: $(form).offset().top}, 800);
        }
        return false;
      });

},
fieldListener: function(field) {
  var className = field.className;
  var classRegExp = /(^| )(\S+)( |$)/g;
  var classResult;
  while (classResult = classRegExp.exec(className)) {
    var oneClass = classResult[2];
    var rule = this.rules[oneClass];
    if (typeof rule != "undefined") {
      if (!rule.test(field.value)) {
        $(field).addClass('invalid').removeClass('valid');
      }
      else {
        $(field).addClass('valid').removeClass('invalid');
      }
    }
  }
},
statusListener: function(form) {
    var failure = false;
  for (var i = 0; i < this.fields.length; i++) {
    var className = this.fields[i].className;
    var classRegExp = /(^| )(\S+)( |$)/g;
    var classResult;
    while (classResult = classRegExp.exec(className)) {
      var oneClass = classResult[2];
      var rule = this.rules[oneClass];
      if (typeof rule != "undefined") {
        if (!rule.test(this.fields[i].value)) {
          failure = true;
        }
      }
    }
  }
  if (failure === true) {
    $('#submit-btn').removeClass('success').attr('disabled', 'disabled');
  }
  else {
    $('#submit-btn').addClass('success').removeAttr('disabled');
  }
},
submitListener: function(form) {
    var failure = false;
    formSentinel.submitting = true;
  for (var i = 0; i < this.fields.length; i++) {
    var className = this.fields[i].className;
    var classRegExp = /(^| )(\S+)( |$)/g;
    var classResult;
    while (classResult = classRegExp.exec(className)) {
      var oneClass = classResult[2];
      var rule = this.rules[oneClass];
      if (typeof rule != "undefined") {
        if (!rule.test(this.fields[i].value)) {
          $(this.fields[i]).removeClass('valid').addClass('invalid');
          failure = true;
        }
        else {
          $(this.fields[i]).removeClass('invalid').addClass('valid');
        }
      }
    }
  }
  if (failure) {
    $('#msg').fadeOut().remove();   
    $('#cf-header').after('<div id="msg" style="display: none;">Your form was not submitted. Please make sure that you have filled out the highlighted fields correctly.</div>');
    $('#msg').fadeIn();
     //}
    formSentinel.submitting = false;
    return false;
  }
  else {
    $.ajax({
        type: 'POST',
        url: '/',
        data: $(form).serialize(),
        success: function(data) {
          if ($(data).find('#success-msg').length > 0) {
            var successMsg = $(data).find('#success-msg');
              $('#msg, p.error, #cf-fieldset').fadeOut().remove();
              $('#cf-header').after('<div id="msg" style="display: none;"></div>');
              $('#msg').html(successMsg);
              $('#msg').fadeIn();
          }
          else if ($(data).find('#error-msg .error').length > 0) {
            var errorMsg = $(data).find('#error-msg .error');
              $('#msg').fadeOut().remove();
              $('#cf-header').after('<div id="msg" style="display: none;"></div>');
              $('#msg').html(errorMsg);
              $('#msg').fadeIn();
          }
          formSentinel.submitting = false;
        }
    });
      }
    }
  }
  $.fn.formSentinel = function() {

    return this.each(function() {
      formSentinel.init(this);
    });

  };

})(jQuery); 


$('#request-form').formSentinel();

$('a[href^="mailto:"]').each(function() {
    var self = $(this);
    var obscuredEmail = this.href.replace(/mailto:/g, '');
    var unobscuredEmail = obscuredEmail.replace(/\/at\//g, '@');
    self.attr('href', 'mailto:' + unobscuredEmail).text(self.text().replace(obscuredEmail, unobscuredEmail));
});

The form itself:

表格本身:

    <form action="#request-form" method="post" id="request-form" class="form" autocomplete="off">
    <input type="hidden" name="consultForm" value="consultForm">          
    <div class="contact-heading project"><h4 id="cf-header">Send direct transmission</h4></div>                  
    <hr class="contactrule" />

    <fieldset id="cf-fieldset">

      <div class="form-field">
      <label for="name">Full Name</label>
        <input type="text" name="name" id="name" placeholder="Full Name" class="requiredNoWhitespace " value="">            
      </div>

      <div class="form-field">
      <label for="email">Email</label>
        <input type="email" name="email" id="email" placeholder="Email" class="requiredNoWhitespace " value="">            
      </div>

      <div class="form-field">
      <label for="phone">Phone Number</label>
        <input type="text" name="phone" id="phone" placeholder="Phone Number" class="requiredNoWhitespace " value="">            
      </div>

      <div class="form-field">
      <label for="type">Project Details</label>
        <input type="text" name="message" id="type" placeholder="Your Message or Project Details" class="requiredNoWhitespace " value="">            
      </div>

      <button type="submit" name="submit" class="submit" id="submit-btn">Transmit</button>
   </fieldset>
 </form>

This is my extremely basic mail.php which I simply grabbed off Google somewhere (I am not overly proficient in PHP at the moment, so...)

这是我非常基本的mail.php,我只是在某个地方抓住了Google(我现在对PHP不太熟练,所以...)

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent=" From: $name \n Phone: $phone \n Message: $message";
$recipient = "theperfectpixels@gmail.com";
$subject = "Sam Norris - Design & Development";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
?>

As usual I would greatly appreciate any help with this!

像往常一样,我非常感谢任何帮助!

1 个解决方案

#1


1  

The form appears to post to the root of the site. Your PHP script (usually index.php) would be there and contain an if to check whether the request type was a POST - then handle the mailing part. Otherwise if the request was a GET then output the JS and HTML in your original post.. Is there any reason this has to be in one page/file?

该表单似乎发布到网站的根目录。您的PHP脚本(通常是index.php)将存在并包含if以检查请求类型是否为POST - 然后处理邮件部分。否则,如果请求是GET,那么在原始帖子中输出JS和HTML ..是否有任何原因必须在一个页面/文件中?

#1


1  

The form appears to post to the root of the site. Your PHP script (usually index.php) would be there and contain an if to check whether the request type was a POST - then handle the mailing part. Otherwise if the request was a GET then output the JS and HTML in your original post.. Is there any reason this has to be in one page/file?

该表单似乎发布到网站的根目录。您的PHP脚本(通常是index.php)将存在并包含if以检查请求类型是否为POST - 然后处理邮件部分。否则,如果请求是GET,那么在原始帖子中输出JS和HTML ..是否有任何原因必须在一个页面/文件中?