我们可以在javascript中使用onsubmit和action一起使用相同的表单吗?

时间:2018-02-11 13:59:04

标签: javascript html

我是javascript的新手,我正在研究更改密码模块。我有两个页面,changepassword.php和change.php。在changepassword.php中,我只是定义元素。在change.php中,我正在处理数据库。它工作正常。这是第一个工作正常的版本代码

changepassword.php

<form action="change.php" method="POST">

<label for="npass">New Password:</label>
<input type="password" id="npass" placeholder="Enter New Password" 
name="newpassword" required="required">

<label for="cpass">Confirm Password:</label>
<input type="password" id="cpass" placeholder="Confirm New Password" 
name="cpass" required="required">
<input type="submit" class="btn btn-info" name="submit" value="Submit">
</form>

change.php

<?php

session_start();

include("dbconn.php");

if(!empty($_POST))
{
    $user_id=$_SESSION['userid'];    
    $npass=$_POST['newpassword'];
    $pas=$_POST['cpass'];

    $que = "update user set password='$npass', last_login='1' where 
    user_id='$user_id' ";

    if ($conn->query($que)==TRUE);
    {
        echo "Password Changed";
        header("Location:home.php");       
    }

}
else
{
    header("changepassword.php");
}

上面的代码工作正常。它按预期更新了表格。现在的问题是,我使用javascript修改了changepassword.php代码以进行验证。更新代码后,数据库中的值不会更新。

修改了changepassword.php

function f1()
{
    var newpass = document.getElementById('npass').value;
    var confirmpass = document.getElementById('cpass').value;

    if(newpass!=confirmpass)
    {
        document.getElementById('npass').value = "";
        document.getElementById('cpass').value = "";
        alert("Password Mismatch. Please enter again!");                
    }
    else
    {
        alert("Password Match");
        window.location.href = "home.php";
    }            
        return false;            
}

<form method="POST" onsubmit="return f1()" action="change.php">


<label for="npass">New Password:</label>
<input type="password" id="npass" placeholder="Enter New Password" 
name="newpassword" required="required" maxlength="8">


 <label for="cpass">Confirm Password:</label>
 <input type="password" id="cpass" placeholder="Confirm New Password" 
 name="cpass" required="required" maxlength="8"><br><br>
 <input type="submit" class="btn btn-info" name="submit" value="Submit">
 </form>

在此之后,不会调用change.php,并且数据库中的值不会更新。任何帮助!感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

if(newpass!=confirmpass)
{
    document.getElementById('npass').value = "";
    document.getElementById('cpass').value = "";
    alert("Password Mismatch. Please enter again!");

    return false;    
} else...