簡體   English   中英

php mail()驗證問題。 不顯示警報,而是打開php表單

[英]php mail() validation problems. Does not show alert, it opens the php form instead

我對php很陌生,需要幫助。 我已經開發了一個php聯系人頁面,但是當字段為空白時,我在驗證方面遇到問題。 當我測試我的驗證時,它會打開php頁面並顯示消息,而不是顯示警報。請參見下面的圖片

驗證問題

這是我的代碼:

HTML:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Exam Portal </title>
    <!--META-->
    <meta name="viewport" content="width=device-width initial-scale=1.0">

    <!--FONT-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,300,700,500' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300' rel='stylesheet' type='text/css'>

    <!--CSS-->
    <link rel="stylesheet" type="text/css" href="css/grid.css"> 
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/responsive.css">
    <link rel="stylesheet" type="text/css" href="css/animate.css">

</head>
<body>
    <div class="se-pre-con">
        <div class="cssload-container">
            <div class="cssload-loading"><i></i><i></i><i></i><i></i></div>
        </div>
    </div>
    <header  style="background-color:black" id="top">
        <div class="container">
            <div class="header-bottom">
                <div class="row">               
                    <div class="col-lg-4 col-md-4 col-sm-5 col-xs-12">                  
                        <div class="logo">
                            <a href="#banner" data-scroll><img src="img/logo.png" alt="" /></a>                 
                        </div>

                    </div>
                    <div class="col-lg-8 col-md-8 col-sm-7 col-xs-12">
                        <nav class="nav-collapse"> 
                            <ul>                    
                                <li class="menu-item"><a href="index.html" data-scroll>HOME</a></li>    
                                <li class="menu-item"><a href="aboutus.html" data-scroll>ABOUT US</a></li>
                                <li class="menu-item"><a href="howdoesitwork.html" data-scroll>HOW DOES IT WORK</a></li>
                                <li class="menu-item"><a href="whousesexamportal.html" data-scroll>WHO USES EP</a></li>
                                <li class="menu-item"><a href="gallery.html" data-scroll>GALLERY</a></li>
                                <li class="menu-item"><a href="news.html"  data-scroll>NEWS</a></li>
                                <li class="menu-item active"><a href="contactus.html" class="btnstart" data-scroll>CONTACT US </a></li>
                            </ul>
                        </nav> 
                    </div>
                </div>
            </div>
        </div>
    </header>   <br><br><br><br><br><br>
  <section id="contact2">
                            <div id="contact-us-map">
                            <iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://www.google.com/maps/embed?pb=!1m23!1m12!1m3!1d114610.04099879299!2d28.110395278010596!3d-26.145762465850492!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m8!3e6!4m0!4m5!1s0x1e9513bfa79eae3f%3A0xabf626720595f367!2shighway+gardens+office+park!3m2!1d-26.1457794!2d28.1804356!5e0!3m2!1sen!2sza!4v1497301543030"></iframe>
                            <br />
                            <small>
                                <a href="https://www.google.co.za/maps/place/Highway+Gardens+Office+Park/@-26.1457794,28.1782469,17z/data=!3m1!4b1!4m5!3m4!1s0x1e9513bfa79eae3f:0xabf626720595f367!8m2!3d-26.14635!4d28.1796255?hl=en"></a>
                            </small>
                            </iframe>
                        </div>
    <div class="container">
      <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12">
         <div class="contact_area">
           <div class="client_title">
              <hr>
              <h2>We Would Love To Hear From You</h2>
            </div>
            <div class="row">
              <div class="col-lg-6 col-md-6 col-sm-6">
                <div class="contact_left wow fadeInLeft">
                  <form method="post" class="submitphoto_form" action="contact.php" id="contactpage">
                    <input type="text" class="form-control wpcf7-text" placeholder="Your name" name="name" id="name">
                    <input type="mail" class="form-control wpcf7-email" placeholder="Email address" name="email" id="email">
                    <input type="text" class="form-control wpcf7-text" placeholder="Subject" name="subject" id="subject">
                    <textarea style="height:300px" class="form-control wpcf7-text" placeholder="What would you like to tell us" name="message" id="message"></textarea>
                    <input type="submit" value="Submit" class="wpcf7-submit photo-submit" name="send" id="send">
                  </form>
                </div>                  
              </div>
              <div class="col-lg-6 col-md-6 col-sm-6">
                <div class="contact_right wow fadeInRight">
                  <img src="img/phone_icon.png" alt="img">
                  <p>Say hello! </p>

                </div>
              </div>
            </div>              
         </div>
        </div>
      </div>
    </div>
  </section>



    <footer>
        <div class="container">
            <div class="row">

                <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                    <div class="footersocial">
                        <i class="fa fa-twitter" aria-hidden="true"></i>
                        <i class="fa fa-facebook" aria-hidden="true" ></i>                                          
                        <i class="fa fa-instagram" aria-hidden="true"></i>
                        <i class="fa fa-dribbble" aria-hidden="true"></i>   
                        <i class="fa fa-gg-circle" aria-hidden="true"></i>  
                    </div>  
                </div>
            </div>
        </div>
    </footer>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="js/fixed-responsive-nav.js"></script>
    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript" src="js/waypoints.min.js"></script>


    <script type="text/javascript">
        jQuery(document).ready(function(){
            //$('#contactpage').validate();
            $('#contactpage').submit(function(){
                var action = $(this).attr('action');

                $.ajax({
                    type: "POST",
                    url: action,
                    data: {
                        name: $('#name').val(),
                        email: $('#email').val(),
                        subject: $('#subject').val(),
                        message: $('#message').val()
                    },
                    dataType: "json",
                    cache: false,
                    success: function (data) {

                        if(data.type == 'success') {
                            alert(data.text);
                        }
                        else {
                            alert(data.text);

                        }

                    }
                });


                    /*$.post(action, {
                            name: $('#name').val(),
                            email: $('#email').val(),
                            subject: $('#subject').val(),
                            message: $('#message').val()
                        },

                        function(data){

                        if(data.type == 'success') {
                            alert("Message sent successfully.");
                        }
                        else {
                            alert("An error occured.");

                        }
                        }
                    );*/

                return false;

            });


        });
    </script>
</body>
</html>

PHP:

<?php



function isEmail($email) {
    return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}

if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");

$name     = $_POST['name'];
$email     = $_POST['email'];
$subject     = $_POST['subject'];
$message     = $_POST['message'];


if(empty($name)) {

    $output = json_encode(array( //create JSON data
        'type'=>'error',
        'text' => 'Please Enter Your Name.'
    ));
    die($output);

} else if(trim($email) == '') {
    $output = json_encode(array( //create JSON data
        'type'=>'error',
        'text' => 'You Have Enter An Invalid E-mail Address, Try Again.'
    ));
    die($output);

}
else if(!isEmail($email)) {
    $output = json_encode(array( //create JSON data
        'type'=>'error',
        'text' => 'You Have Enter An Invalid E-mail Address, Try Again.'
    ));
    die($output);
}
else if(empty($subject)) {

    $output = json_encode(array( //create JSON data
        'type'=>'error',
        'text' => 'Please Enter Your Mail Subject.'
    ));
    die($output);

}
else if(empty($message)) {

    $output = json_encode(array( //create JSON data
        'type'=>'error',
        'text' => 'Please Enter Your Message.'
    ));
    die($output);

}

else {

    $fromMail = $email;
    $toMail = "myemail@gmail.com";
    $boundary = str_replace(" ", "", date('l jS \of F Y h i s A'));
    $subjectMail = "Contact Form From $name | Examportal";

    $body = "Name :  $name <br/>
                  Email: $email <br/>
                  Message Title : $subject <br/>
                  Message : \n $message
                  ";
    $contentHtml = '
            <div style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#333;">
                <div style="color:#565656;">'.$body.'</div>
            </div>
            <div style="clear:both"></div>
        ';
    $headersMail = '';
    $headersMail .= 'From: ' ."noreply@emailexample.co.za\r\n" . 'Reply-To: ' . $fromMail . "\r\n";
    $headersMail .= 'Return-Path: ' . $fromMail . "\r\n";
    $headersMail .= 'MIME-Version: 1.0' . "\r\n";
    $headersMail .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";

    try {
        if (mail($toMail, $subjectMail, $contentHtml, $headersMail)) {
            $output = json_encode(array( //create JSON data
                'type'=>'success',
                'text' => 'Thank you for contacting us, we will get back to you real soon. :).'
            ));
            die($output);

        } else {
            $output = json_encode(array( //create JSON data
                'type'=>'error',
                'text' => 'An unknown error occuredx. Please try again later.'
            ));
            die($output);

        }
    } catch(Exception $e) {
        $msg = $e->getMessage();
        $output = json_encode(array( //create JSON data
            'type'=>'error',
            'text' => 'Error occur with message : '.$msg
        ));
        die($output);

    }



}












?>

驗證任何空白字段的最簡單方法是在輸入HTML中添加required ,如下所示。

<form method="post" class="submitphoto_form" action="contact.php" id="contactpage">
    <input type="text" class="form-control wpcf7-text" placeholder="Your name" name="name" id="name" required>
    <input type="email" class="form-control wpcf7-email" placeholder="Email address" name="email" id="email" required>
    <input type="text" class="form-control wpcf7-text" placeholder="Subject" name="subject" id="subject" required>
    <textarea style="height:300px" class="form-control wpcf7-text" placeholder="What would you like to tell us" name="message" id="message" required></textarea>
    <input type="submit" value="Submit" class="wpcf7-submit photo-submit" name="send" id="send">
</form>

另請注意,您輸入的電子郵件類型應為“電子郵件”,而不是“郵件”。

使用PHP驗證的缺點是用戶將不得不重新輸入所有字段。

使用JS驗證的缺點是,如果用戶禁用了JS,則驗證將無法進行。

使用簡單的HTML驗證的好處是,它將在所有瀏覽器上都可以工作,並且在任何空白字段和​​/或無效的電子郵件格式的情況下將停止提交表單。

使用這種方法,您不需要使用JS進行驗證。 它是純HTML。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM