使用Ajax / PHP的单选按钮值

时间:2014-06-05 14:50:04

标签: php jquery ajax html5 email-validation

我的邮件列表订阅的显然简单表单存在问题。

HTML5表单包含3个字段:

    电子邮件地址的
  1. 文字输入<input type="email" name="email"
  2. 单选按钮控件有2个选项:
    • <input type="radio" value="subscribe" name="radio"
    • <input type="radio" value="unsubscribe" name="radio"
  3. 文字输入 CAPTCHA 检查:<input type="text" name="captchavalue"

        

        <form id="contact" name="contact" method="post" action="index.php" enctype="multipart/form-data">
        <input type="hidden" name="check" value="01">
        <small>*tutti i campi sono obbligatori</small>
    
        <label for="email" id="emailabel">E-mail:<span class="err topp">INDIRIZZO NON VALIDO</span></label>
        <input type="email" name="email" id="email" class="textemail">
    
        <label for="subscr" id="subscrlabel">Scelta:<span class="err topp">devi selezionare una scelta</span></label>
        <p><input type="radio" name="radio" id="radio" value="subscribe" checked>Iscrizione</p>
        <p><input type="radio" name="radio" id="radio" value="unsubscribe">Cancellazione</p>
    
        <img src="captcha.php" id="captchaimg">
        <label for="captcha" id="captchalabel">Copiare il codice di verifica<span class="err capter">CAPTCHA ERRATO</span></label>
        <input type="text" name="captchavalue" id="captchavalue" class="textcaptcha">
    
        <section id="subber">
        <a href="javascript:void(0);" name="submitlink" id="submitlink" class="btn">Invia richiesta</a>
        </section>
    
        </form>
    
    </div>
    

  4. 我们有一个允许在外部文件.dat中包含请求订阅的域列表,PHP中的某些行动态创建正则表达式以检查电子邮件地址(仅在订阅的情况下,否则为任何有效的电子邮件地址是允许的)

    <?php
    
        $domains = file("domains.dat");
        $domcount = count($domains);
        for ($i=0; $i < $domcount; $i++) {
            $regex .= "(".trim($domains[$i]).")|";
        }
        $regex = str_replace(".", "\.", $regex);
        $regex = "/^([a-zA-Z\.-_0-9]*@(".substr($regex, 0, strlen($regex)-1).")$)/i";
    ?>
    
    function checkValidCNRAddress(emailAddress) {
        var pattern = new RegExp(<? echo $regex ?>);
    
        return pattern.test(emailAddress);
    };
    
    function checkValidEmailAddress(emailAdd) {
        var pattern = new RegExp(/^(("[\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][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    
        return pattern.test(emailAdd);
    };
    
    var mailsendstatus;
    function userSendMailStatus(uemail,usubscr, ucaptcha) {
    
        // statement below is for DEBUG purposes only -- to show the
        // value of the radio button (subscription status) in ALL CASES
        document.write(usubscr); //DEBUG
    
        //check that a radio button option is checked (default: "subscribe" is checked )
        if(!usubscr) {
            $("#subscrlabel").children(".err").fadeIn('slow');
        }
        else if(usubscr) {
          // we have *something* selected in the radio button for subscription
          $("#subscrlabel").children(".err").fadeOut('slow');   
    
                // next, check for validate email addresses using regular expressions
            //check on dynamic regex 
            if (usubscr == "subscribe") {   
                if(!checkValidCNRAddress(uemail)) {
                    $("#emailabel").children(".err").fadeIn('slow');
                }
                else if(checkValidCNRAddress(uemail)) {
                    $("#emailabel").children(".err").fadeOut('slow');   
                }
            } //else check at least for a valid email address
            else if (usubscr == "unsubscribe"){ 
                if(!checkValidEmailAddress(uemail)) {
                    $("#emailabel").children(".err").fadeIn('slow');
                }
                else if(checkValidEmailAddress(uemail)) {
                    $("#emailabel").children(".err").fadeOut('slow');   
                }
            }       
        }
    

    然后检查验证码是否正常(它将数据发送到PHP页面captcha_check)然后提交给sendmail.php(负责将订阅/取消订阅请求发送到我们的邮件服务器)

        // captcha check
        $.ajax(
            {
                type: 'POST',
                url: 'captcha_check.php',
                data: $("#contact").serialize(),
                success: function(data) {
                    if(data == "false") {
                        mailsendstatus = false;
                        $("#captchalabel").children(".err").fadeIn('slow');
                    }
                    else if(data == "true"){
                        $("#captchalabel").children(".err").fadeOut('slow');
    
                        if((checkValidCNRAddress(uemail))||(checkValidEmailAddress(uemail))) {
                            // in this case it's alright
                            // TRUE
                            mailsendstatus = true;
    
                            $("#subber").html('<img src="img/load.gif" alt="loading...">');
    
                            $.ajax(
                                {
                                    type: 'POST',
                                    url: 'sendmail.php',
                                    data: $("#contact").serialize(),
                                    success: function(data) {
                                        if(data == "yes") {
                                        $("#contactwrapper").slideUp(650, function(){
                                            $(this).before("<p>La tua richiesta è stata inviata, grazie.</p>");
                                        });
                                        }
                                    }
                                }
                            ); // 
                        } // 
                    } // 
                } //
            } // 
        );
    
        return mailsendstatus;
    }
    
    $(document).ready(function(){
        $("#contact").submit(function() { return false; });
    
        $("#submitlink").bind("click", function(e){
            var usercaptvalue = $("#captchavalue").val();
            var emailvalue    = $("#email").val();
            var subscrvalue    = $("#radio").val();
    
            //sends values to sendmail.php
            var postchecks = userSendMailStatus(emailvalue, subscrvalue, usercaptvalue);
        });
    });
    </script>
    
    </body>
    

    有人可以向我解释一下: - 当脚本验证电子邮件地址时,给定的单选按钮的值总是&#34;订阅&#34;,无论如何,即使我检查取消订阅 - 但是如果我输入一个域名包含在domains.dat中的电子邮件地址并检查按钮是否取消订阅,则传递给sendmail.php的值是&#34;取消订阅&#34; (正如我收到电子邮件时所看到的那样)

    希望它足够清楚......提前感谢您的宝贵帮助!

1 个答案:

答案 0 :(得分:1)

您的问题是, NOT 实际向sendmail.php发送任何 AJAX 请求,除非该电子邮件有效当电子邮件有效时,

您会看到,您在JavaScript中检查有效电子邮件地址的所有验证都是然后:

  • 淡化您的错误 =&gt; $("#subscrlabel").children(".err").fadeIn('slow');

<强>

  • 淡出错误OUT =&gt; $("#subscrlabel").children(".err").fadOut('slow');

但是,这只发生在

页面上

当您实际提交时,如果电子邮件无效,它将无法通过AJAX请求,但是,它仍然正常提交表单,因此它会重置为默认订阅输入状态“已检查”

在关闭功能后,您需要做的是在验证中包含.ajax(...)声明/调用,而不是在其下面:

var mailsendstatus;
function userSendMailStatus(uemail,usubscr, ucaptcha) {
  //verify radio button (it's checked by default in our case)
   if(!usubscr) {
       $("#subscrlabel").children(".err").fadeIn('slow');
   }
   else {
       $("#subscrlabel").children(".err").fadeOut('slow'); 

       //check on dynamic regex 
       if (usubscr == "subscribe") {   
           if(!checkValidCNRAddress(uemail)) {
               $("#emailabel").children(".err").fadeIn('slow');
           }
           else if(checkValidCNRAddress(uemail)) {
               $("#emailabel").children(".err").fadeOut('slow');   
                mailsendstatus = true;
           }
        } //else check at least for a valid email address
        else if (usubscr == "unsubscribe"){ 
            if(!checkValidEmailAddress(uemail)) {
                $("#emailabel").children(".err").fadeIn('slow');
            }
            else if(checkValidEmailAddress(uemail)) {
                $("#emailabel").children(".err").fadeOut('slow');   
                mailsendstatus = true;
            }
        }       
    }
    if (mailsendstatus = true;) {
      ...
      //make your AJAX request here
      ...
    }
}