PHP / Javascript验证部分工作

时间:2017-11-27 06:05:29

标签: javascript php jquery ajax

我的表单有Javascript / Ajax和PHP验证。如果表单填写不正确,它会显示错误,但它不会工作,即使没有错误也让我提交表单。基本上,当我点击提交按钮时,它会停留在同一页面上并且不会做任何事情。 在控制台中,我在提交时收到了下一个错误:无法加载文件:/// C:/Users/ilona/Desktop/BootstrapLandinPage/send.php:仅支持协议方案的交叉原始请求:http,data,chrome,chrome -extension,https。的jquery-2.2.4.min.js:4。我在XAMPP上运行我的项目。

我的HTML:

<section class="inspiration" id="three">
            <div class="overlay">
                <div class="container">
                    <div class="row">
                        <article class="col-md-12 text-center">
                            <div class="intermediate-container">
                                <div class="heading">
                                    <h2>יש לכם שאלה? צרו איתי קשר</h2>
                                </div>
                                <div class="row">
                                    <div class="col-md-3 col-sm-3"></div>
                                    <div class="col-md-6 center-block col-sm-6 ">
                                        <form id="mc-form" method="POST">
                                            <div class="form-group col-xs-12 ">
                                                <label for="name" hidden>שם פרטי</label>
                                                <input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי">
                                                <span class='error-message' id='name-error'></span>

                                            </div>
                                            <div class="form-group col-xs-12 ">
                                                <label for="phone" hidden>טלפון</label>
                                                <input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון">
                                                <span class='error-message' id='phone-error'></span>
                                            </div>
                                            <div class="form-group col-xs-12 ">
                                                <label for="email" hidden>דואר אלקטרוני</label>
                                                <input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני">
                                                <span class='error-message' id='email-error'></span>
                                            </div>
                                            <div class="form-group col-xs-12 ">
                                                <label for="subject" hidden>נושא</label>
                                                <input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא">
                                                <span class='error-message' id='subject-error'></span>
                                            </div>
                                            <div class="form-group col-xs-12 ">
                                                <label for="message" hidden>הודעה</label>
                                                <textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
                                                <span class='error-message' id='message-error'></span>
                                            </div>
                                            <!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
                                            <button class="btn btn-custom-outline " id="submit-button">שלח</button>
                                            <span class='error-message' id='submit-error'></span>
                                            <span class="success">Thank's for submitting the form</span>

                                        </form>
                                    </div>
                                </div>
                            </div>
                        </article>
                    </div>
                </div>
            </div>
        </section>
        <!-- [/CONTACT] -->



        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validateform.js" ></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>

我的validateform.js:

$(document).ready(function(){

        function jsShow(id) {
            $('#'+id).show();
        }

        function jsHide(id) {
            $('#'+id).hide();
        }

        function producePrompt(message, promptLocation, color) {

            $('#'+promptLocation).text(message).css('color', color).show();

        }

        jQuery.validator.addMethod("lettersonly", function(value, element) {
            return this.optional(element) || /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i.test(value);
        }, "Letters only please");
        jQuery.validator.addMethod("digitsonly", function(value, element) {
            return this.optional(element) || /([0-9\s\-]{7,})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/.test(value);
        }, "Include only digits| min :8 ");

        $('.success').hide();

        $("#mc-form").validate({
            error: function(label) {
                $(this).addClass( "error" );
            },
            rules: {
                name: {
                    required: true,
                    lettersonly: true
                },
                phone: {
                    required: true,
                    digitsonly: true
                },
                email: {
                    required: true,
                    email: true
                },
                subject: {
                    required: true,
                    minlength: 2
                },
                message: {
                    required: true,
                    minlength: 2
                }
            },
            messages: {
                name: {
                    required: "Please specify your name",
                    lettersonly: "Letters only please"
                },
                phone: {
                    required: "Phone number is required",
                    digitsonly: "Include only digits| min :8 "
                },
                email: {
                    required: "Email is required",
                    email: "Email Invalid"
                },
                subject: {
                    required: "Subject is required"
                },
                message: {
                    required: "Message is required"
                }
            },
            submitHandler: function(form) {
                sendForm();
            }
        });

        function sendForm() {

            $('[id*="-error"]').text(''); // default hide all error messages

            event.preventDefault(); // prevent form submission and therefore page reload

            $.ajax({
                type: 'POST',
                url: './send.php',
                data: $("#mc-form").serialize(),
                success: function(data) {

                    if(data.hasOwnProperty('error')) {

                        Object.keys(data['error']).forEach(function(key) {
                            producePrompt(data['error'][key], key+'-error', 'red');
                        });

                    }
                    if(data.hasOwnProperty('mail_error')) {
                        alert('Could not send mail');
                    }
                    if(data.hasOwnProperty('success')) {
                        $('.success').show();
                    }
                }
            });

        }

    });

我的send.php:

$error_msg = array();
$success_msg = array();
$data = '';

// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
        $error_msg['name'] = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
            $error_msg['name'] = "Only letters and white space allowed";
        }
    }


    if (empty($_POST["email"])) {
        $error_msg['email'] = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error_msg['email'] = "Invalid email format";
        }
    }

    if (empty($_POST["phone"])) {
        $error_msg['phone'] = "Phone is required";
    } else {
        $phone = test_input($_POST["phone"]);
        // check if e-mail address is well-formed
        if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
            $error_msg['phone'] = "Invalid phone number";
        }
    }
    if (empty($_POST["subject"])) {
        $error_msg['subject'] = "Subject is required";
    }
    if (empty($_POST["message"])) {
        $error_msg['message'] = "Message is required";
    }

    if (empty($_POST["subject"])) {
        $subject = "";
    } else {
        $subject = test_input($_POST["subject"]);
    }

    if (empty($_POST["message"])) {
        $message = "";
    } else {
        $message = test_input($_POST["message"]);
    }

    if (empty($error_msg)){ // note that $lastname_error does not exists
        $message_body = '';
        unset($_POST['submit']);
        foreach ($_POST as $key => $value){
            $message_body .=  "$key: $value\n";
        }

        $to = 'xxxxxxxxx@gmail.com';
        $subjectm = 'Contact Form Submit';
        if (mail($to, $subjectm, $message)){
            $success_msg = "Message sent, thank you for contacting us!";
            $name = $email = $phone = $message = $subject = '';
        } else {
            $mail_error_msg = 'Could not send email';
        }


    }

    // set output data accordingly
    if(!empty($success_msg)) {
        $data = array('success'=>$error_msg);
    } else if(!empty($error_msg)) {
        $data = array('error'=>$error_msg);
    } else if(!empty($mail_error_msg)) {
        $data = array('mail_error'=>$mail_error_msg);
    }

    // output json that you can parse with jquery
    header('Content-Type: application/json');
    echo json_encode($data);
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

0 个答案:

没有答案