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条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘