Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过PHP在JavaScript验证后将表单数据发送到mySQL数据库_Javascript_Php_Mysql_Ajax_Validation - Fatal编程技术网

通过PHP在JavaScript验证后将表单数据发送到mySQL数据库

通过PHP在JavaScript验证后将表单数据发送到mySQL数据库,javascript,php,mysql,ajax,validation,Javascript,Php,Mysql,Ajax,Validation,我有一个html表单用作订阅表单。表单通过POST方法发送到PHP文件进行处理和数据库输入。表单验证是通过JavaScript完成的 我不想重定向到PHP文件,我想保持我的表单样式。也就是说,当用户单击SUBMIT按钮时,表单将在页面上设置动画并显示一条成功消息,而无需重新加载或发送到php文件 我已经单独测试了PHP文件,它运行良好,在mySQL数据库表中按预期编写。 JavaScript验证文件本身也非常有效。问题是,当单击Submit按钮时,在所有必填字段都有效之后,表单会显示为数据发送成

我有一个html表单用作订阅表单。表单通过POST方法发送到PHP文件进行处理和数据库输入。表单验证是通过JavaScript完成的

我不想重定向到PHP文件,我想保持我的表单样式。也就是说,当用户单击SUBMIT按钮时,表单将在页面上设置动画并显示一条成功消息,而无需重新加载或发送到php文件

我已经单独测试了PHP文件,它运行良好,在mySQL数据库表中按预期编写。 JavaScript验证文件本身也非常有效。问题是,当单击Submit按钮时,在所有必填字段都有效之后,表单会显示为数据发送成功,但没有数据写入我的数据库。我尝试在JavaScript代码中的不同位置插入不同格式的AJAX,但没有任何效果


JS验证文件链接到HTML文件中的via。PHP文件通过表单Action=属性链接到

当我在HTML中与form.js链接一起使用以下脚本时:

 <script type="text/javascript">
$("#submitBtn").click(function() {
    var dataString = $('#register').serialize();
    $.ajax({   
                    type: "POST",
                    url: "contact/validate.php",
                    data: dataString
            });

});
</script>

这里有几点不清楚。1您的JS验证文件位于何处,如何启动?2在你的问题段落所展示的脚本中,你在成功时什么都不做;更多信息,请不要阻止默认设置,以便表单提交。JS验证文件在HTML文件中链接到via。PHP文件通过表单Action=属性链接到。成功时你什么都不做是什么意思?拜托,我来这里是因为我对JavaScript和PHP非常熟悉。另外,正如我所指出的,HTML文件中的AJAX调用确实有效并将数据发送到数据库,但它绕过了单独的form.js文件中的验证规则。它不会阻止单击最终导致提交表单,因此validate.php脚本将执行两次:首先通过Ajax url,然后通过表单操作。为了避免这种情况,您应该添加returnfalse;在单击功能的末尾。从这一点开始,然后我们可以考察成功的方面。谢谢你的时间,cFreed!非常感谢所以,$submitBtn.clickfunction{var dataString=$'register'。序列化;$.ajax{type:POST,url:contact/validate.php,data:dataString};返回false;};这对于防止在数据库中写入无效的表单数据仍然没有任何效果。在更深入地检查JS验证文件后,我开始理解:这是您当前通知preventDefault的地方。但关键是:由于验证文件中的事件处理程序阻止了默认值,因此另一个事件处理程序中的$.ajax调用不会执行!在我看来,验证文件要么做了太多的工作,要么至少应该包含Validation.php调用。如果能提供一些说明来指出/解释发布的代码,我将不胜感激。这是一个很好的说明。不过,我需要的是电子邮件检查和添加最小字符检查,以确保发送到数据库的数据是有效的,而不仅仅是一些随机键入。
 <div id="contactForm" class="contactForm">
<div id="formHeader" class="formHeader">
    <h2 id="message">Форма за регистрация</h2>
</div>
<div id="formBody" class="formBody">
    <form action="contact/validate.php" method="POST" name="contactForm"   id="register">
        <div class="row">
        <div class="inputContainer hlf">
            <input name="fullname" id="fullname" type="text" placeholder="Вашето име" minlength="2" maxlength="40" required tabindex="1">
        </div>
        <div class="inputContainer hlf">
            <input name="location" id="location" type="text" placeholder="Населено място" minlength="5" maxlength="40" required tabindex="2">
        </div>
        </div>
        <div class="row">
        <div class="inputContainer hlf">
            <input name="email" id="email" type="email" placeholder="Ваш имейл за контакт" maxlength="75" required tabindex="3">
        </div>
            <div class="inputContainer hlf">
            <input name="phone" id="phone" type="tel" placeholder="Телефон" pattern="[0-9 ]" maxlength="15" tabindex="4">
        </div>
        </div>
        <div class="row">
        <div class="inputContainer">
            <textarea name="comment" id="comment" rows="4" placeholder="Допълнителен коментар" minlength="5" maxlength="250" tabindex="5"></textarea>
        </div></div>
        <input id="submitBtn" class="submitBtn" type="submit" value="Изпрати">
    </form>
</div>
<?php
//Clean form data from backslashes and evil tags
//define variables and set to empty values
$fullname = $location = $email = $phone = $comment = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$location = test_input($_POST["location"]);
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$comment = test_input($_POST["comment"]);
}

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

//All input is tested and validated, now connect to DB and send data to the    mySQL database table:

$servername = "localhost";
$username = "usename";
$password = "password";
$dbname = "database name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO subscribed (fullname, location, email, phone, comment)
VALUES ('$fullname', '$location', '$email', '$phone', '$comment')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
$(function() {
"use strict";
var //GLOBAL VARIABLES
input,
        container,
        //CSS CLASSES
        classSuccess = "success",
        classError = "error",
        //FORM VALIDATOR
        formValidator = {
            init: function() {
                this.cacheDom();
                this.bindEvents();
            },
            cacheDom: function() {
                //MAIN PARENT ELEMENT
                this.contactForm = document.getElementById("contactForm");
                //MAIN FORM ELEMENTS
                this.formHeader = document.querySelector("#formHeader h2");
                this.formBody = document.getElementById("formBody");
                this.inputContainer = document.getElementsByClassName("inputContainer");
                //USER INPUT ELEMENTS
                //INPUT FIELDS
                this.fields = {
                    fullname: document.getElementById("fullname"),
                    location: document.getElementById("location"),
                    email: document.getElementById("email")
                };
                this.submitBtn = document.getElementById("submitBtn");
            },
            bindEvents: function() {
                var i;
                //RUN RULES ON SUBMIT BUTTON CLICK
                this.submitBtn.onclick = this.runRules.bind(this);
                //BIND EVENTS TO EACH INPUT FIELD
                for (i in this.fields) {
                    if (this.fields.hasOwnProperty(i)) {
                        //VARIABLES
                        input = this.fields[i];
                        container = input.parentElement;
                        //RUN RULES WHEN INPUT HAS FOCUS
                        input.onfocus = this.runRules.bind(this);
                        //RESET ERRORS WHEN CONTAINER IS CLICKED
                        container.onclick = this.resetErrors.bind(this, input);
                    }
                }
            },
            runRules: function(evnt) {
                var target = evnt.target,
                        type = evnt.type;
                //IF EVENT ON SUBMIT BUTTON
                if (target === this.submitBtn) {
                    //PREVENT FORM SUBMITTION
                    this.preventDefault(evnt);
                    //IF INPUT HAS FOCUS
                } else if (type === "focus") {
                    //RESET CLASSLIST
                    this.resetClassList(target.parentElement);
                    //RESET ERRORS
                    this.resetErrors(target);
                    return false;
                }
                //RESET CLASSLIST
                this.resetClassList();
                //CHECK FIELDS
                this.checkFields();
            },
            preventDefault: function(evnt) {
                //PREVENT DEFUALT
                evnt.preventDefault();
            },
            checkFields: function() {
                var i,
                        validCount = 0,
                        //EMAIL FILTER 
                        filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                //CYLCE THROUGH INPUTS
                for (i in this.fields) {
                    if (this.fields.hasOwnProperty(i)) {
                        input = this.fields[i];
                        //CHECK IF FIELD IS EMPTY
                        if (input.value === "") {
                            //ADD ERROR CLASS
                            this.addClass(input, classError);
                            //CHECK IF EMAIL IS VALID
                        } else if (i === "email" && !filter.test(input.value)) {
                            //ADD ERROR CLASS
                            this.addClass(input, classError);
                        } else {
                            //FIELD IS VALID
                            this.addClass(input, classSuccess);
                            validCount += 1;
                        }
                    }
                }
                //IF ALL FIELDS ARE VALID
                if (validCount === 3) {
                    //SUBMIT FORM
                    this.submitForm();
                }
            },
            addClass: function(input, clss) {
                container = input.parentElement;
                //IF INPUT HAS ERROR
                if (clss === classError) {
                    //SHOW ERROR MESSAGE
                    this.errorMessage(input);
                }
                //ADD CLASS
                input.parentElement.classList.add(clss);
            },
            errorMessage: function(input) {
                var message;
                //IF NAME HAS ERROR
                if (input === this.fields.fullname) {
                    message = "Моля, въведете пълно име";
                    //ELSE IF LOCATION HAS ERROR 
                } else if (input === this.fields.location) {
                    message = "Моля, въведете град/село";
                    //ELSE IF USEREMAIL HAS ERROR
                } else if (input === this.fields.email) {
                    message = "Има грешка в имейла";
                }
                this.renderError(input, message);
            },
            renderError: function(input, message) {
                var html;
                //GET INPUT CONTAINER
                container = input.parentElement;
                //RENDER HTML
                html = document.createElement("div");
                html.setAttribute("class", "message");
                html.innerHTML = message;
                //IF MESSAGE ELEMENT DOESN'T EXIST
                if (!container.getElementsByClassName("message")[0]) {
                    //INSERT MESSAGE TO INPUT CONTAINER
                    container.insertBefore(html, container.firstElementChild);
                }
            },
            resetClassList: function(input) {
                var i;
                //IF TARGETING SPECIFIC INPUT
                if (input) {
                    //GET INPUT CONTAINER
                    container = input.parentElement;
                    //REMOVE CLASSES
                    container.classList.remove(classError, classSuccess);
                    //FOCUS ON INPUT FIELD
                    input.focus();
                } else {
                    for (i in this.fields) {
                        if (this.fields.hasOwnProperty(i)) {
                            //REMOVE CLASSES FROM ALL FIELDS
                            this.fields[i].parentElement.classList.remove(classError, classSuccess);
                        }
                    }
                }
            },
            resetErrors: function(input) {
                //GET INPUT CONTAINER
                container = input.parentElement;
                //IF CONTAINER CONTAINS ERROR
                if (container.classList.contains(classError)) {
                    //RESET CLASSES
                    this.resetClassList(input);
                }
            },
            submitForm: function() {
                var waitForAnimation;
                //ADD SUCCESS CLASS
                this.contactForm.classList.add(classSuccess);
                //WAIT FOR ANIMATION TO FINISH
                this.changeHeader("Регистрацията е успешна!");
                //WAIT FOR ANIMATION TO FINISH
                setTimeout(this.changeHeader.bind(this, "ДОБРЕ ДОШЛИ!"), 1800);
            },
            changeHeader: function(text) {
                //CHANGE HEADER TEXT
                this.formHeader.innerHTML = text;
            }
        };
//INITIATE FORM VALIDATOR
formValidator.init();
}());
<!DOCTYPE html>
<html>
<head>
    <title>Task 1</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function()
        {
            $("#submit").click(function()
            {
                if($("#fname").val()=="")
                {
                    alert("First name missing");
                    return false;
                }
                if($("#lname").val()=="")
                {
                    alert("Last name missing");
                    return false;
                }
                var x= jQuery("input[name=gender]:checked").val();
                if(!x)
                {
                    alert("Gender missing");
                    return false;
                }
                var x= jQuery("input[type=checkbox]:checked").val();
                if (!x)
                {
                    alert("Hobbies not selected");
                    return false;
                }
                if($("#education").val()=="") 
                {
                    alert("Select Education");
                    return false;
                }
                else
                {
                    return true;
                }
            });
        });
    </script>
</head>
<body>
<form action="insert.php" method="POST" name="myform">
    <table border="2" cellspacing="5" cellpadding="5" align="center">
        <tr>
            <td>
                Enter first name:
            </td>
            <td>
                <input type="text" name="fname" id="fname">
            </td>
        </tr>
        <tr>
            <td>
                Enter last name:
            </td>
            <td>
                <input type="text" name="lname" id="lname">
            </td>
        </tr>
        <tr>
            <td>
                Select gender:
            </td>
            <td>
                <input type="radio" name="gender" value="male" id="gender">Male
                <input type="radio" name="gender" value="female">Female
            </td>
        </tr>
        <tr>
            <td>
                Select hobbies:
            </td>
            <td>
                <input type="checkbox" name="hobbies[]" value="cricket" id="hobby">Cricket
                <input type="checkbox" name="hobbies[]" value="hockey">Hockey
                <input type="checkbox" name="hobbies[]" value="swimming">Swimming
            </td>
        </tr>
        <tr>
            <td>
                Select education:           
            </td>
            <td>
                <select name="education" id="education">
                    <option value="">Select...</option>
                    <option value="MCA">MCA</option>
                    <option value="BCA">BCA</option>
                    <option value="BE">BE</option>
                </select>
            </td>
        </tr>
        <tr align="center">
            <td colspan="2">
                <input type="submit" name="submit" value="Submit" id="submit">
            </td>
        </tr>
    </table>
    </form>
</body>
</html>