带有 PHP 回退的 jQuery 联系表单


jQuery Contact Form with PHP fallback

我按照本教程学习如何使用PHP和jQuery制作联系表单。据我所知,这个想法是让jquery工作,php作为"备份"。

我按照教程学习,没有任何问题。或者我是这么想的...但最终似乎jQuery不起作用。验证时我总是得到"闪烁"(页面刷新)。

这是我尝试使用它的页面:http://dccf.site88.net/test/dccf.php

这是 PHP:

// Set email variables
$email_to = 'luis_bento@hotmail.com';
$email_subject = 'Message from DCCF site';
// Set required fields
$required_fields = array('fullname','email','comment');
// set error messages
$error_messages = array(
    'fullname' => 'Please enter a Name to proceed.',
    'email' => 'Please enter a valid Email.',
    'comment' => 'Please enter a Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
    // Sanitise POST array
    foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
    // Loop into required fields and make sure they match our needs
    foreach($required_fields as $field) {       
        // the field has been submitted?
        if(!array_key_exists($field, $_POST)) array_push($validation, $field);
        // check there is information in the field?
        if($_POST[$field] == '') array_push($validation, $field);
        // validate the email address supplied
        if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
    }
    // basic validation result
    if(count($validation) == 0) {
        // Prepare our content string
        $email_content = 'New Website Comment: ' . "'n'n";
        // simple email content
        foreach($_POST as $key => $value) {
            if($key != 'submit') $email_content .= $key . ': ' . $value . "'n";
        }
        // if validation passed ok then send the email
        mail($email_to, $email_subject, $email_content);
        // Update form switch
        $form_complete = TRUE;
    }
}
function validate_email_address($email = FALSE) {
    return (preg_match('/^[^@'s]+@([-a-z0-9]+'.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
   return (str_ireplace(array("'r", "'n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>


        <div id="formWrap">
    <h2>If you like our project, have any questions, or would like more information, please send us a message.</h2><!-- end of "Form Message" h2 -->
    <div id="form">
    <?php if($form_complete === FALSE): ?>
    <form action="dccf.php" method="post" id="comments_form">
        <div  class="row">
            <div class="label">Your Name:</div><!-- end of .label -->
            <div class="input">
                <input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /><?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
            <div class="context">e.g. John Smith or Jane Doe</div><!-- end of .context --> 
        </div><!-- end of .row -->
        <div  class="row">
            <div class="label">Your Email:</div><!-- end of .label -->
            <div class="input">
                <input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
            <div class="context">e.g. youremail@somewhere.com</div><!-- end of .context --> 
        </div><!-- end of .row -->
        <div  class="row">
            <div class="label">Your Message:</div><!-- end of .label -->
            <div class="input">
                <textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea><?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
        </div><!-- end of .row -->
        <div class="submit">
            <input type="submit" id="submit" name="submit" value"Send Message" />
        </div><!-- end of .submit -->
        </form>
        <?php else: ?>
        <p class="thanks">Thank you for your Message! We will get back to you as soon as possible.</p>
        <?php endif; ?>
    </div><!-- end of #form -->
</div><!-- end of #formWrap -->

和 Java 脚本:在 :

    <script type="text/javascript">
    var nameError = '<?php echo $error_messages['fullname']; ?>';
    var emailError = '<?php echo $error_messages['email']; ?>';
    var commentError = '<?php echo $error_messages['comment']; ?>';
</script>

在验证中.js:

    window.addEvent('domready', function() {
// Get the form
var form = $('comments_form');
//  if the form is found...
if (form) {
    // obtain error fields
    var name = $('fullname');
    var email = $('email');
    var comment = $('comment');
    // Set the default status
    var isValid = true;
    // input error function for the error messages
    var addError = function (field, msg) {
        field.addClass('error'); // Add error class to field
        var error = field.getParent().getElement('span') || new Element('span', {'class': 'error'}); // add error message if not already placed
        error.set('text', msg); // error text msg
        error.inject(field, 'after'); // Insert error message after field
    };
    // detach error function used to delete any error messages and remove the error class
    var removeError = function (field) {
        field.removeClass('error'); // Remove error class from form fields
        var error = field.getParent().getElement('span'); // find any existing error messages
        // destroy if error message
        if (error) {
            error.destroy();
        }
    };
    //  insert submit form event
    form.addEvent('submit', function (e) {
        // Test name length
        if (name.get('value').length === 0) {
            isValid = false;
            addError(name, nameError);
        } else {
            isValid = true;
            removeError(name);
        }
        // check email length
        if (email.get('value').length === 0) {
            isValid = false;
            addError(email, emailError);
        // check email validity
        } else if (!email.get('value').test(/^([a-zA-Z0-9'+_'-]+)('.[a-zA-Z0-9'+_'-]+)*@([a-zA-Z0-9'-]+'.)+[a-zA-Z]{2,6}$/)) {
            isValid = false;
            addError(email, emailError);
        } else {
            isValid = true;
            removeError(email);
        }
        // check comment length
        if (comment.get('value').length === 0) {
            isValid = false;
            addError(comment, commentError);
        } else {
            isValid = true;                     
            removeError(comment);
        }
        // If form invalid then stop event happening
        if (!isValid) {
            e.stop();
        }
    });
}   
});

感谢您的帮助!=)

编辑:控制台上出现一些错误(加载页面时,而不是提交表单时):

  • 视口参数键"width_device宽度"无法识别和忽略。 DCCF.php:8
  • TypeError: 'undefined' 不是函数(评估 'form.addEvent') 验证.js:4

我已经删除了我之前的答案,因为你的代码有很多问题。

这是删除所有错误的jQuery等效项,因此它

  1. 如果只填写了后面的一个字段,则不再允许提交
  2. 没有使用 string.test(regex
  3. ),而是使用正确的 regex.test(string)
  4. 使用全名而不是姓名作为名称字段
  5. 重置每次按下提交时都有效

演示

$(function() {
  // Get the form
  var form = $('#comments_form');
  //  if the form is found...
  if (form) {
    // input error function for the error messages
    var addError = function (field, msg) {
        field.addClass('error'); // Add error class to field
        var error = field.parent().find('span') || $('<span>', {'class': 'error'}); // add error message if not already placed
        error.html(msg); // error text msg
        field.after(error); // Insert error message after field
    };
    // detach error function used to delete any error messages and remove the error class
    var removeError = function (field) {
        field.removeClass('error'); // Remove error class from form fields
        var error = field.parent().find('span'); // find any existing error messages
        // destroy if error message
        if (error) {
            error.remove();
        }
    };
    //  insert submit form event
    form.on('submit', function (e) {

        // Set the default status
        var isValid = true;
        // Test name length
        var name = $("#fullname");
        if (name.val().length === 0) {
            isValid = false;
            addError(name, nameError);
        } else {
            removeError(name);
        }
        // check email length
        var email = $("#email");
        var emailVal = email.val();
        if (emailVal.length === 0) {
            isValid = false;
            addError(email, emailError);
        // check email validity
        } else if (!/^([a-zA-Z0-9'+_'-]+)('.[a-zA-Z0-9'+_'-]+)*@([a-zA-Z0-9'-]+'.)+[a-zA-Z]{2,6}$/.test(emailVal)) {
            isValid = false;
            addError(email, emailError);
        } else {
            removeError(email);
        }
        // check comment length
        var comment = $("#comment");
        console.log(comment.val())
        if (comment.val().length === 0) {
            isValid = false;
            addError(comment, commentError);
        } else {
            removeError(comment);
        }
        // If form invalid then stop event happening
        if (!isValid) {
            e.preventDefault();
        }
    });
  }   
});