如果表单中出现错误,则在提交表单时对话框应该保持打开状态


If errors in form, then dialog box should stay open when form is submit

我有一个注册对话框,其中有一个登录表单。我已经做了一些基本的表单验证在相同的文件作为表单,如果存在错误,然后适当的消息回显在字段下,当表单提交。

然而,当提交表单时,页面被刷新,对话框关闭,用户必须再次打开它才能看到错误。这是不太合适的和我想以某种方式保持对话框打开刷新,只有当错误存在于表单验证

一定有办法解决这个问题,但我不太知道如何实现这个。

下面是我的代码(index.php):
    // PHP validation
    $fornameErr = $surnameErr ="";
    $forname = $surname="";

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["forename"])) {
            $fornameErr = "Missing";
        }
        else {
            $forename= $_POST["forename"];
        }
        if (empty($_POST["surname"])) {
            $surnameErr= "Missing";
        }
        else {
            $surname= $_POST["surname"];
        }
}

// Link which opens up the dialog box by calling the 'check_domain_input()' function
<div id="clickable" onclick="check_domain_input()">Or <a href="#">sign up</a></div>
// The form in the dialog box
<div id="dialog" title="Sign up" style="display:none">    
    <center>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <div align="center">
       <br/>       
       <input type="text" class="input" name="forename" size="20" maxlength="40" placeholder="Forename" value="<?php echo htmlspecialchars($forename);?>"/> 
        <span class="error"><?php echo $fornameErr ;?></span>
        <br/>
        <input type="text" class="input" name="surname" size="20" maxlength="40" placeholder="Surname" value="<?php echo htmlspecialchars($surname);?>"/> 
        <span class="error"><?php echo $surnameErr ;?></span>
        <br/>
    <input type="submit" value ="Sign up" class="submit"/>
    <br/>
    <br/>
    </div>
  </form>   
  </center>
    </div>

<!-- Dialog box function -->
<script>
    function check_domain_input()
    {        
        $( "#dialog" ).dialog({modal: true}); 
        var domain_val = document.getElementsByName('domain');       
        if (domain_val[0].value.length > 0)
        {
            return true;
        }     
        $( "#dialog" ).dialog({modal: true});
        return false;
    }
</script>

您可以在页面加载时调用您的check_domain_input方法,如果您有一个错误显示,像这样:

<script>
    function check_domain_input()
    {        
        ...
    }
<?php if (!empty($fornameErr) || !empty($surnameErr)) : ?>
    $(function() {
        check_domain_input();
    });
<?php endif; ?>
</script>
  1. 您可以使用onsubmit="return validateFunction()",如下链接所示。
  2. 你可以让PHP设置一个JavaScript变量,你的jQuery onload函数读取和响应。
  3. 你可以使用AJAX代替表单提交。使用AJAX,您可以简单地使用AJAX调用的error函数来响应错误的验证。