使用PHP,Ajax和Jquery更改密码

时间:2016-05-11 16:39:52

标签: php jquery mysql ajax

我想我需要一个有更好眼光的人帮助我发现我的错误。我正在尝试更改当前密码而不刷新页面。我收到错误消息“错误,请再试一次!”。到目前为止,这是我的代码。

HTML

<form name="resetform" action="changepass.php" id="resetform" class="passform" method="post" role="form">
  <h3>Change Your Password</h3>
  <br />
  <input type="hidden" name="username" value="<?php echo $sname;?>" ></input>
  <label>Enter Old Password</label>
  <input type="password" class="form-control" name="old_password" id="old_password">
  <label>Enter New Password</label>
  <input type="password" class="form-control" name="new_password" id="new_password">
  <label>Confirm New Password</label>
  <input type="password" class="form-control"  name="con_newpassword"  id="con_newpassword" />
 <br>
 <input type="submit" class="btn btn-warning" name="password_change" id="submit_btn" value="Change Password" />
</form>

PHP

<?php
include_once 'database-config.php';

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

    $username = strip_tags($_POST['sname']);
    $password = strip_tags($_POST['old_password']);
    $newpassword = strip_tags($_POST['new_password']);
    $confirmnewpassword = strip_tags($_POST['con_newpassword']);

// match username with the username in the database
    $sql = "SELECT * FROM users WHERE username='$sname'";

    $query = $dbh->prepare($sql);

    $query->execute();

    $row = $query->fetchAll();

    $hash = $row[0]["password"];

    //$hash = $results[0]["password"];

        if ($password == $hash){

            if($newpassword == $confirmnewpassword) {

            $sql = "UPDATE users SET password = '$newpassword' WHERE    username  = '$username'";

            $query = $dbh->prepare($sql);

            $query->execute();

            echo "Password Changed Successfully!";

        } else echo "Passwords do not match!";
        }
    } else echo "Please type your current password accurately!";
}
?>

Jquery的

<script type="text/javascript">
$(document).ready(function() {
        var frm = $('#resetform');
        frm.submit(function(e){
            $.ajax({
                type: frm.attr('method'),
                url: frm.attr('action'),
                data: frm.serialize(),
                success: function(data){
                    $('#success').html("<div id='message'></div>");
                    $('#message').html("<h2>Password changed successfully!</h2>")
                    .delay(3000).fadeOut(3000);
                },
                error: function(data) {
                    $('#error').html("<div id='errorMessage'></div>");
                    $('#errorMessage').html("<h3>Error, please try again!</h3>")
                    .delay(2000).fadeOut(2000);
                }

            });

            e.preventDefault();
        });
    });
</script>

我将不胜感激任何更正: - )

3 个答案:

答案 0 :(得分:1)

您的代码存在一些问题,例如:

  • 请在此处查看此声明,

    if (isset($_POST['password_change'])) { ...
    

    此处,$_POST['password_change']未设置,因为jQuery的serialize()不包含编码按钮或提交输入,因此您必须将提交按钮的名称和值附加到结果中,如下所示:< / p>

    var formData = frm.serialize();
    formData += '&' + $('#submit_btn').attr('name') + '=' + $('#submit_btn').attr('value');
    
  • 由于此声明

    ,未设置变量$username
    $username = strip_tags($_POST['sname']);
    

    应该是,

    $username = strip_tags($_POST['username']);
    
  • 在另一个元素中创建一个元素以显示成功/错误消息是没有意义的,并且无论查询结果如何,消息都是相同的。另外,您没有使用服务器的响应data。请参阅AJAX请求中的以下回调函数,

    success: function(data){
        $('#success').html("<div id='message'></div>");
        $('#message').html("<h2>Password changed successfully!</h2>")
        .delay(3000).fadeOut(3000);
    },
    error: function(data) {
        $('#error').html("<div id='errorMessage'></div>");
        $('#errorMessage').html("<h3>Error, please try again!</h3>")
        .delay(2000).fadeOut(2000);
    }
    

    相反,请创建一个div元素:

    <div id="message"></div>
    

    并在回调函数中显示成功/错误消息,如下所示:

    success: function(data){
        $('#message').html(data).delay(3000).fadeOut(3000);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        $('#message').html(textStatus).delay(2000).fadeOut(2000);
    }
    
  • PHP代码中包含Parse error: syntax error, unexpected '}' in ...的语法错误很少。

  • 始终准备绑定执行您的查询以防止任何类型的SQL注入。 And this is how you can prevent SQL injection in PHP

  • 永远不要将密码存储为简单易读的文本,在将密码插入表格之前,请始终对原始密码执行salted password hashing

所以你的代码应该是这样的:

<强> HTML:

<form name="resetform" action="changepass.php" id="resetform" class="passform" method="post" role="form">
    <h3>Change Your Password</h3>
    <br />
    <input type="hidden" name="username" value="<?php echo $sname; ?>" ></input>
    <label>Enter Old Password</label>
    <input type="password" class="form-control" name="old_password" id="old_password">
    <label>Enter New Password</label>
    <input type="password" class="form-control" name="new_password" id="new_password">
    <label>Confirm New Password</label>
    <input type="password" class="form-control"  name="con_newpassword"  id="con_newpassword" />
    <br>
    <input type="submit" class="btn btn-warning" name="password_change" id="submit_btn" value="Change Password" />
</form>

<!--display success/error message-->
<div id="message"></div>

<强> jQuery的:

$(document).ready(function() {
    var frm = $('#resetform');
    frm.submit(function(e){
        e.preventDefault();

        var formData = frm.serialize();
        formData += '&' + $('#submit_btn').attr('name') + '=' + $('#submit_btn').attr('value');
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: formData,
            success: function(data){
                $('#message').html(data).delay(3000).fadeOut(3000);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $('#message').html(textStatus).delay(2000).fadeOut(2000);
            }

        });
    });
});

<强> PHP:

<?php

    include_once 'database-config.php';

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

        $username = strip_tags($_POST['username']);
        $password = strip_tags($_POST['old_password']);
        $newpassword = strip_tags($_POST['new_password']);
        $confirmnewpassword = strip_tags($_POST['con_newpassword']);

        // match username with the username in the database
        $sql = "SELECT * FROM `users` WHERE `username` = ? LIMIT 1";

        $query = $dbh->prepare($sql);
        $query->bindParam(1, $username, PDO::PARAM_STR);

        if($query->execute() && $query->rowCount()){
            $hash = $query->fetch();
            if ($password == $hash['password']){
                if($newpassword == $confirmnewpassword) {
                    $sql = "UPDATE `users` SET `password` = ? WHERE `username` = ?";

                    $query = $dbh->prepare($sql);
                    $query->bindParam(1, $newpassword, PDO::PARAM_STR);
                    $query->bindParam(2, $username, PDO::PARAM_STR);
                    if($query->execute()){
                        echo "Password Changed Successfully!";
                    }else{
                        echo "Password could not be updated";
                    }
                } else {
                    echo "Passwords do not match!";
                }
            }else{
                echo "Please type your current password accurately!";
            }
        }else{
            echo "Incorrect username";
        }
    }

?>

答案 1 :(得分:0)

在此更改

$username = strip_tags($_POST['username']);//not sname

答案 2 :(得分:0)

您的表单未提交,因为jQuery的.serialize()未包含input type=submit中的值,因此PHP的if (isset($_POST['password_change'])) {失败。

检查出来:jQuery serializeArray doesn't include the submit button that was clicked

我还会在您的AJAX中包含更好的错误处理。尝试这样的事情:

$.ajax({
    type: "post", 
    url: "",
    success: function (data) {
        //...
    },
    error: function (request, status, error) {
        console.log(request);
        console.log(status);
        console.log(error);
    }
});