表单/ PHP脚本在提交后根据需要清除表单,提交但不清除Chrome和Firefox中的表单

时间:2017-11-17 18:25:45

标签: javascript php jquery forms

为什么这个PHP /表单在Edge中提交并清除,但Chrome和Firefox中的表单提交在提交后没有清除表单。

最终结果将是Edge提交表单,弹出成功消息然后从表单中清除数据。在Chrome和Firefox中,它都会提交数据,但成功消息和表单不会清除,允许多次提交相同的表单。

这是表格:

    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/haydon.css" type="text/css" media="screen">
    <script src="js/jquery-1.7.1.min.js"></script>
    <script src="js/script.js"></script>
    <script src="js/forms.js" type="text/javascript"></script>
    </head>
        <form id="contact-form" method="post" action="../bin/Mailhandler.php">
        <div class="success">Contact form submitted!
            <br><strong>We will be in touch soon.</strong>
        </div>
        <fieldset>
            <label class="name">
                <input type="text" value="Name:"><span class="error">*This is not a valid name.</span><span class="empty">*This field is required.</span>
            </label>
            <label class="email">
                <input type="text" value="E-mail:"><span class="error">*This is not a valid email address.</span><span class="empty">*This field is required.</span>
            </label>
            <label class="phone">
                <input type="tel" value="Phone:"><span class="error">*This is not a valid phone number.</span><span class="empty">*This field is required.</span>
            </label>
            <label class="message">
                <textarea>Message:</textarea><span class="error">*The message is too short.</span><span class="empty">*This field is required.</span>
            </label>
            <div class="buttons-wrapper"><a class="button" data-type="reset">Clear</a><a class="button" data-type="submit">Submit</a>
            </div>
        </fieldset>
        </form>

PHP脚本:

<?php
//SMTP server settings  
$host = "smtp.blanked.com";
$port = "587";
$username = "smtpform@blanked.com";
$password = "Blanked";
$messageBody = "";

if($_POST['name']!='false'){
    $messageBody .= '<p>Visitor: ' . $_POST["name"] . '</p>' . "\n";
    $messageBody .= '<br>' . "\n";
}

if($_POST['email']!='false'){
    $messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n";
    $messageBody .= '<br>' . "\n";
}else{
    $headers = '';
}

if($_POST['state']!='false'){       
    $messageBody .= '<p>State: ' . $_POST['state'] . '</p>' . "\n";
    $messageBody .= '<br>' . "\n";
}

if($_POST['phone']!='false'){       
    $messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n";
    $messageBody .= '<br>' . "\n";
}   

if($_POST['fax']!='false'){     
    $messageBody .= '<p>Fax Number: ' . $_POST['fax'] . '</p>' . "\n";
    $messageBody .= '<br>' . "\n";
}

if($_POST['message']!='false'){
    $messageBody .= '<p>Message: ' . $_POST['message'] . '</p>' . "\n";
}

if($_POST["stripHTML"] == 'true'){
    $messageBody = strip_tags($messageBody);
}

if($host=="" or $username=="" or $password==""){
    $owner_email = $_POST["owner_email"];
    $headers = 'From:' . $_POST["owner_email"] . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n";
    $subject = 'A message from your site visitor ' . $_POST["name"];

    try{
        if(!mail($owner_email, $subject, $messageBody, $headers)){
            throw new Exception('mail failed');
            }else{
            echo 'mail sent';
        }

        }catch(Exception $e){
        echo $e->getMessage() ."\n";
    }

}else{  
    require_once 'Mail.php';

    $to = $_POST["owner_email"];
    $subject = 'A message from your site visitor ' . $_POST["name"];
    $headers = array (
    'From' => 'From:' . $_POST["owner_email"] . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n",
    'To' => $to,
    'Subject' => $subject);

    $smtp = Mail::factory(
                'smtp',
                array (
                    'host' => $host,
                    'port' => $port,
                    'auth' => true,
                    'username' => $username,
                    'password' => $password));

    $mail = $smtp->send($to, $headers, $messageBody);

    try{
        if(PEAR::isError($mail)){
            echo $mail->getMessage();
            }else{
            echo 'mail sent';
        }
        }catch(Exception $mail){
        echo $mail->getMessage() ."\n";
    }
}   
?>

这是forms.js

(function ($) {
$.fn.forms = function (o) {
    return this.each(function () {
        var th = $(this),
            _ = th.data('forms') || {
                errorCl: 'error',
                emptyCl: 'empty',
                invalidCl: 'invalid',
                notRequiredCl: 'notRequired',
                successCl: 'success',
                successShow: '4000',
                mailHandlerURL: 'http://www.blankeddomain.co.uk/bin/Mailhandler.php',
                ownerEmail: '',
                stripHTML: true,
                smtpMailServer: 'localhost',
                targets: 'input,textarea',
                controls: 'a[data-type=reset],a[data-type=submit]',
                validate: true,
                rx: {
                    ".name": {
                        rx: /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,
                        target: 'input'
                    },
                    ".state": {
                        rx: /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,
                        target: 'input'
                    },
                    ".email": {
                        rx: /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,
                        target: 'input'
                    },
                    ".phone": {
                        rx: /^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,
                        target: 'input'
                    },
                    ".fax": {
                        rx: /^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,
                        target: 'input'
                    },
                    ".message": {
                        rx: /.{20}/,
                        target: 'textarea'
                    }
                },
                preFu: function () {
                    _.labels.each(function () {
                        var label = $(this),
                            inp = $(_.targets, this),
                            defVal = inp.val(),
                            trueVal = (function () {
                                var tmp = inp.is('input') ? (tmp = label.html().match(/value=['"](.+?)['"].+/), !! tmp && !! tmp[1] && tmp[1]) : inp.html()
                                return defVal == '' ? defVal : tmp
                            })()
                            trueVal != defVal && inp.val(defVal = trueVal || defVal)
                            label.data({
                                defVal: defVal
                            })
                            inp
                                .bind('focus', function () {
                                    inp.val() == defVal && (inp.val(''), _.hideEmptyFu(label), label.removeClass(_.invalidCl))
                                })
                                .bind('blur', function () {
                                    _.validateFu(label)
                                    if (_.isEmpty(label))
                                        inp.val(defVal), _.hideErrorFu(label.removeClass(_.invalidCl))
                                })
                                .bind('keyup', function () {
                                    label.hasClass(_.invalidCl) && _.validateFu(label)
                                })
                            label.find('.' + _.errorCl + ',.' + _.emptyCl).css({
                                display: 'block'
                            }).hide()
                    })
                    _.success = $('.' + _.successCl, _.form).hide()
                },
                isRequired: function (el) {
                    return !el.hasClass(_.notRequiredCl)
                },
                isValid: function (el) {
                    var ret = true
                    $.each(_.rx, function (k, d) {
                        if (el.is(k))
                            ret = d.rx.test(el.find(d.target).val())
                    })
                    return ret
                },
                isEmpty: function (el) {
                    var tmp
                    return (tmp = el.find(_.targets).val()) == '' || tmp == el.data('defVal')
                },
                validateFu: function (el) {
                    el.each(function () {
                        var th = $(this),
                            req = _.isRequired(th),
                            empty = _.isEmpty(th),
                            valid = _.isValid(th)

                            if (empty && req)
                                _.showEmptyFu(th.addClass(_.invalidCl))
                            else
                                _.hideEmptyFu(th.removeClass(_.invalidCl))

                            if (!empty)
                                if (valid)
                                    _.hideErrorFu(th.removeClass(_.invalidCl))
                                else
                                    _.showErrorFu(th.addClass(_.invalidCl))
                    })
                },
                getValFromLabel: function (label) {
                    var val = $('input,textarea', label).val(),
                        defVal = label.data('defVal')
                        return label.length ? val == defVal ? 'nope' : val : 'nope'
                },
                submitFu: function () {
                    _.validateFu(_.labels)
                    if (!_.form.has('.' + _.invalidCl).length)
                        $.ajax({
                            type: "POST",
                            url: _.mailHandlerURL,
                            data: {
                                name: _.getValFromLabel($('.name', _.form)),
                                email: _.getValFromLabel($('.email', _.form)),
                                phone: _.getValFromLabel($('.phone', _.form)),
                                fax: _.getValFromLabel($('.fax', _.form)),
                                state: _.getValFromLabel($('.state', _.form)),
                                message: _.getValFromLabel($('.message', _.form)),
                                owner_email: _.ownerEmail,
                                stripHTML: _.stripHTML
                            },
                            success: function () {
                                _.showFu()
                            }
                        })
                },
                showFu: function () {
                    _.success.slideDown(function () {
                        setTimeout(function () {
                            _.success.slideUp()
                            _.form.trigger('reset')
                        }, _.successShow)
                    })
                },
                controlsFu: function () {
                    $(_.controls, _.form).each(function () {
                        var th = $(this)
                        th
                            .bind('click', function () {
                                _.form.trigger(th.data('type'))
                                return false
                            })
                    })
                },
                showErrorFu: function (label) {
                    label.find('.' + _.errorCl).slideDown()
                },
                hideErrorFu: function (label) {
                    label.find('.' + _.errorCl).slideUp()
                },
                showEmptyFu: function (label) {
                    label.find('.' + _.emptyCl).slideDown()
                    _.hideErrorFu(label)
                },
                hideEmptyFu: function (label) {
                    label.find('.' + _.emptyCl).slideUp()
                },
                init: function () {
                    _.form = _.me
                    _.labels = $('label', _.form)

                    _.preFu()

                    _.controlsFu()

                    _.form
                        .bind('submit', function () {
                            if (_.validate)
                                _.submitFu()
                            else
                                _.form[0].submit()
                            return false
                        })
                        .bind('reset', function () {
                            _.labels.removeClass(_.invalidCl)
                            _.labels.each(function () {
                                var th = $(this)
                                _.hideErrorFu(th)
                                _.hideEmptyFu(th)
                            })
                        })
                    _.form.trigger('reset')
                }
            }
        _.me || _.init(_.me = th.data({
            forms: _
        }))
        typeof o == 'object' && $.extend(_, o)
    })
}
})(jQuery)
$(window).load(function () {
    $('#contact-form').forms({
        ownerEmail: 'blanked@domain.co.uk'
    })
})

此时,任何来自其他目光的方向或建议都会受到赞赏。

0 个答案:

没有答案