I'm currently working on a form that allows the user to change their password. And I'm not very good with jQuery ajax. The ajax doesn't seem to send the data to changepassword.php. The PHP file works fine when I don't use ajax. Can you guys help me out here a bit?
I updated my files according to some of the comments. When I try to submit the form, it returns Doesn't Work. So I guess the php is responding, but the value didn't get to the database.
Thanks a lot for the help guys.
Following is the form and ajax (Updated)
<form id="form_id" method="POST">
<label for="username">Username</label>
<input type="text" name="username" id="username" required />
<label for="old_password">Old Password</label>
<input type="password" name="old_password" id="old_password" required />
<label for="new_password">New Password</label>
<input type="password" name="new_password" id="new_password" required />
<button class="submit">
Submit
</button>
<p class="result"></p>
</form>
<script>
$.ajaxSetup({
cache : false
});
$(".submit").click(function(e) {
$.ajax({
url : "changepassword.php",
type : "POST",
data : $("#form_id").serialize(),
success : function(data) {
if(data == 1) {
$(".result").html("Works");
} else {
$(".result").html("Doesn't Work");
}
}
});
return false;
});
</script>
And this is changepassword.php (Updated)
<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);
include_once "../classes/Connect.php";
$connection = new Connect();
$username = $_POST['username'];
$old_password = $_POST['old_password'];
$new_password = $_POST['new_password'];
$result = $connection -> change_password($username, $old_password, $new_password);
if ($result) {
echo 1;
}
?>
This is the method change_password() from connect.php class file
function change_password($username, $old_password, $new_password){
$query = "UPDATE Account SET password = ? WHERE username = ? AND password = ?";
if ($stmt = $this -> conn -> prepare($query)){
$stmt -> bind_param('sss', md5($new_password), $username, md5($old_password));
if ($stmt -> execute()){
return true;
}
}
}
$.ajaxSetup ({cache:false})at top of your script.