0

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

GeekBoi
  • 23
  • 2
  • 7
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure that you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard May 11 '16 at 16:44
  • I dont think this is the issue but In your PHP, you have an open curly `{` missing after the last `else` – CodeGodie May 11 '16 at 16:47
  • The error message you see is coming from the error handler in your AJAX call, not your PHP. That means the request itself failed. Open your browser console and look for errors. Is the path correct? – WillardSolutions May 11 '16 at 16:47
  • `if ($password == $hash)` I see the word "hash", but you're not updating the db with a hash; *wassup with that?* – Funk Forty Niner May 11 '16 at 16:55
  • possible duplicate of [PHP: “Notice: Undefined variable” and “Notice: Undefined index”](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Funk Forty Niner May 11 '16 at 16:57
  • another possible duplicate [PHP Parse/Syntax Errors; and How to solve them?](http://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them) too many errors in your code. – Funk Forty Niner May 11 '16 at 17:03

3 Answers3

1

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

?>
Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • wow! Thanks. Worked like a charm. Thanks everyone for pointing out my errors, I'm surely going to work on improving myself. Thanks @Jay Blanchard for pointing out the password security issues. – GeekBoi May 12 '16 at 14:47
0

Change here

$username = strip_tags($_POST['username']);//not sname
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

Your form is not submitting because jQuery's .serialize() does not include the value in input type=submit therefore PHP's if (isset($_POST['password_change'])) { fails.

Check this out: jQuery serializeArray doesn't include the submit button that was clicked

I would also include better error handling in your AJAX. Try something like this:

$.ajax({
    type: "post", 
    url: "",
    success: function (data) {
        //...
    },
    error: function (request, status, error) {
        console.log(request);
        console.log(status);
        console.log(error);
    }
});
Community
  • 1
  • 1
CodeGodie
  • 12,116
  • 6
  • 37
  • 66