douzhaiyuan1731 2016-05-11 16:39
浏览 50
已采纳

使用PHP,Ajax和Jquery更改密码

I think i need someone with a better eye to help me spot my error. I am trying to change the current password without refreshing the page. I get the error message "Error, please try again!". This is my code so far.

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>

i would appreciate any corrections :-)

  • 写回答

3条回答 默认 最新

  • doutou1922 2016-05-11 19:27
    关注

    There are several issues with your code, such as:

    • See this statement here,

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

      Here, $_POST['password_change'] is not set becacuse jQuery's serialize() does not include encoding buttons or submit inputs, so you have to append the name and value of the submit button to your result, like this:

      var formData = frm.serialize();
      formData += '&' + $('#submit_btn').attr('name') + '=' + $('#submit_btn').attr('value');
      
    • The variable $username is not set because of this statement,

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

      It should be,

      $username = strip_tags($_POST['username']);
      
    • There's no point creating an element inside another element to display the success/error message, and also the message would be same irrespective of the outcome of the query. Plus you're not making use of server's response data. See these following callback functions in your AJAX request,

      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);
      }
      

      Instead, make a div element like this:

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

      And display the success/error message in your callback functions like this:

      success: function(data){
          $('#message').html(data).delay(3000).fadeOut(3000);
      },
      error: function(jqXHR, textStatus, errorThrown) {
          $('#message').html(textStatus).delay(2000).fadeOut(2000);
      }
      
    • There are few syntax errors comprising of Parse error: syntax error, unexpected '}' in ...in your PHP code.

    • Always prepare, bind and execute your queries to prevent any kind of SQL injection. And this is how you can prevent SQL injection in PHP.

    • Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.

    So your code should be like this:

    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";
            }
        }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路