简体   繁体   English

如何验证HTML表单并与PHP脚本进行交互

[英]How to validate an html form and interact with php script

I have this html form that interacts with a MySQL database created in XAMPP . 我有这个html表单,它与XAMPP创建的MySQL数据库进行交互。 I'd like to validate it in such a way that once controlled the first two boxes(Name and Email areas) are filled it sends the message to the database using a php script I wrote. 我想以一种方式验证它,即一旦控制了前两个框(名称和电子邮件区域)被填充,它就会使用我编写的php脚本将消息发送到数据库。 I have written the javascript code to validate the form, but it works even if the first two fields are not filled, so it's wrong in some way. 我已经编写了JavaScript代码来验证表单,但是即使前两个字段没有填写,它也可以工作,因此在某种程度上是错误的。 Here are the files(html, javascript and php): 以下是文件(html,javascript和php):

html form html表格

<html>

<header>

    <script type="text/javascript" src="javascript/validateForm.js"></script>

    <?php include("connectivity.php"); ?>
</header>

<body>

<form name="contactForm" id="contactForm" method="post" action="connectivity.php">
        <div class="form_settings">
            <p><span>Name and Surname</span>
                <input type="text" name="nome" id="nome" />
            </p>
            <p><span>Email</span>
                <input type="text" name="email" id="email" />
            </p>
            <p><span>Message</span>
                <textarea rows="8" cols="50" name="messaggio" id="messaggio"></textarea>
            </p>
            <p style="padding-top: 15px"><span>&nbsp;</span>
                <input class="submit" type="submit" name="invia" value="Invia" onclick="checkForm()" />
            </p>
        </div>
    </form>

</body>
</html>

javascript file to validate(it is wrong in some way) 要验证的javascript文件(某种方式是错误的)

function exists(input) {
    atLeastOneChar = false;
    if (input) {
        for (i = 0; i < input.length; i++) {
            if (input.charAt(i) != " ") {
                atLeastOneChar = true;
                break;
            }
        }
    }
    return atLeastOneChar;
}

function checkForm() {
    mes = "";
    if (!exists(document.contactForm.nome.value))
        mes = mes + "Missing name\n";
    if (!exists(document.contactForm.email.value))
        mes = mes + "Missing email\n";
    if (mes != "")
        alert(mes);
    if (mes == "") {
        alert("Ok, correct!\nThe form should now be sent to " +
            "the server!");

    }
} 

php file to interact with database php文件与数据库交互

<?php


    $db = new PDO('mysql:host=localhost;dbname=myprojectdb;charset=utf8', 
                  'root', 
                  '',
                  array(PDO::ATTR_EMULATE_PREPARES => false,
                  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));


?>
    <?php

if (isset($_POST['nome'])) {

    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $messaggio =  $_POST['messaggio'];



    $stmt = $db->prepare("INSERT INTO `contatti` (contattoNome,contattoEmail,messaggio)
    VALUES (:nome, :email, :messaggio)");
    $stmt->bindParam(':nome', $nome);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':messaggio', $messaggio);

    $stmt->execute();

    echo 'email inviata correttamente';

}

?>

How can I solve this problem? 我怎么解决这个问题?

Instead of trying to get your own validation to work. 而不是试图让自己的验证生效。 It's much easier using a jQuery Validation plugin like: 使用jQuery Validation插件要容易得多,例如:

https://github.com/jzaefferer/jquery-validation https://github.com/jzaefferer/jquery-validation

Or I prefer: 或者我更喜欢:

http://parsleyjs.org/ http://parsleyjs.org/

They are pretty straight forward to implement. 他们非常直接地实施。

Are you sure that this is actually returning the correct result? 您确定这实际上返回了正确的结果吗?

!exists(document.contactForm.nome.value)

Because it seems to me that a "value" will exist whether it's populated with something or not. 因为在我看来,无论是否填充某些东西,“值”都会存在。 Have you tried: 你有没有尝试过:

docuemnt.getElementById("nome").value != '';

Also, your button is of type "submit". 另外,您的按钮的类型为“提交”。 It's going to submit whatever happens regardless of the message. 无论消息如何,它都会提交任何发生的事情。 You should change that to "button". 您应该将其更改为“按钮”。

EDIT: added code for button type: 编辑:添加按钮类型的代码:

<input class="submit" type="button" name="invia" value="Invia" onclick="checkForm()" />

Then, in your code: 然后,在您的代码中:

if (mes == "") {
        alert("Ok, correct!\nThe form should now be sent to " +
            "the server!");
        document.getElementById("contactForm").submit();
    }

Javascript functions should return false if validation fails and you should call js validation function in onsubmit event in form. 如果验证失败,则Javascript函数应返回false,您应该在onsubmit事件中以表单形式调用js验证函数。 Replace these two lines. 替换这两行。

1)javascript file to validate if (mes != ""){ alert(mes); 1)用于验证(mes!=“”){alert(mes); return false // add this line in js file } 返回false //在js文件中添加此行}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM