Change mysql password using PHP and AJAX - php

I'm trying to make a change password modal. My problem is that if I want to update my password, it prints: "Incorrect username". How can I solve this problem? I'm using the password = PASSWORD method to hash the password. I'm trying to bind param with the $_SESSION["username"] but it didn't work.
index.php
<form name="resetform" action="changepass.php" id="resetform" class="passform" method="post" role="form">
<h3>Change Your Password</h3>
<br />
<input type="text" name="username" value="<?php echo $_SESSION["username"]; ?>" ></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>
<script>
$(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);
}
});
});
});
</script>
changepass.php
include_once 'include/connection.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 `user` WHERE `username` = ? AND password = PASSWORD(?)";
$query = $connect->prepare($sql);
$query->bindParam(1, $username, PDO::PARAM_STR);
$query->bindParam(2, $password, PDO::PARAM_STR);
if($query->execute() && $query->rowCount()){
$hash = $query->fetch();
if ($password == $hash['password']){
if($newpassword == $confirmnewpassword) {
$sql = "UPDATE `user` SET `password` = PASSWORD(?) WHERE `username` = ?";
$query = $connect->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";
}
}

Your first major issue is your use of strip_tags, I'm not sure who told you to do that on input, but it's an incredibly bad practice. If you strip tags on password inputs, you're downgrading the security of any password that uses a <.
strip_tags('A<dsf$tgee!'); // a strong password of 'A<dsf$tgee!' becomes a weak password of 'A'.
This condition will also never evaluate to true:
$password == $hash['password']
Password is hashed via MySQL's PASSWORD() function so the plain text $password will never match the password column in MySQL.

Related

Can I use jQuery to dynamically style a form after it's validated with PHP?

I'm trying to add styling to certain parts of my form based on what happens in my PHP script. For example, I'd like to add a class to an input that the user fills out incorrectly that will trigger CSS rules, such as making the input's border red.
I thought I might be able to do this using jQuery at the end of my PHP script, but I haven't been successful despite writing it several different ways. I checked to make sure my new CSS styling came after the default styling too. It may also be worthwhile to mention that I'm using AJAX to validate as well, so the user stays on the registration page if the form is not filled out properly.
Here is my PHP script (jQuery is at the end):
<?php
if (isset($_POST['submit']))
{
include_once "_databaseHandler.php";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$confirmPassword = mysqli_real_escape_string($connection,
$_POST['confirmPassword']);
$errorEmpty = false;
//Check for empty fields
if (empty($username) || empty($email) || empty($password) ||
empty($confirmPassword))
{
echo "<span class='form-error'>Please fill in all fields</span>";
$errorEmpty = true;
}
else
{
$sqlUsername = "SELECT * FROM userinfo WHERE userName = '$username'";
$resultUsername = mysqli_query($connection, $sqlUsername);
$resultCheckUsername = mysqli_num_rows($resultUsername);
$sqlEmail = "SELECT * FROM userinfo WHERE userEmail = '$email'";
$resultEmail = mysqli_query($connection, $sqlEmail);
$resultCheckEmail = mysqli_num_rows($resultEmail);
//Check length of username
if (strlen($username) < 4)
{
echo "<span class='form-error'>Your username must be at least 4
characters long</span>";
$errorEmpty = true;
}
//Check if username is taken
else if ($resultCheckUsername > 0)
{
echo "<span class='form-error'>This username is already
taken</span>";
$errorEmpty = true;
}
//many other checks with exact same syntax using else if...
//Insert the user into the database
else
{
$sql = "INSERT INTO userinfo (userName, userEmail, userPassword) VALUES (?, ?, ?);";
$statement = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($statement, $sql))
{
echo "<span class='form-error'>Database error</span>";
exit();
}
else
{
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($statement, "sss", $username, $email, $hashedPassword);
mysqli_stmt_execute($statement);
$emailSubject = "wtf";
$emailMessage = "Hello my son";
mail($email, $emailSubject, $emailMessage);
session_start();
$_SESSION['register-success'] = 'You have successfully registered! Please verify your email before logging in.';
echo
"<script type=\"text/javascript\">
window.location.href='../index.php';
</script>";
exit();
}
}
}
}
else
{
header('Location: ../index.php');
exit();
}
?>
<reference path="jquery-3.3.1.min.js"/>
<script type="text/javascript">
var errorEmpty = "<?php echo $errorEmpty; ?>";
if (errorEmpty)
{
$("#register-username").addClass(".input-error");
}
</script>
Full context of related code:
jQuery:
/// <reference path="jquery-3.3.1.min.js" />
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var username = $("#register-username").val();
var email = $("#register-email").val();
var password = $("#register-password").val();
var confirmPassword = $("#register-confirm-password").val();
var submit = $("#register-submit").val();
$(".form-message").load("../shared/_registerAccount.php", {
username: username,
email: email,
password: password,
confirmPassword: confirmPassword,
submit: submit
});
});
});
HTML:
<?php
include "shared/_header.php";
?>
<div class="wrapper-register">
<div id="register-account">
<div class="register-title">
<h2>REGISTER ACCOUNT</h2>
</div>
<form action="shared/_registerAccount.php" method="post">
<div class="register-input">
<input id="register-username" type="text" name="username"
maxlength="16" placeholder="Username" />
</div>
<div class="register-input">
<input id="register-email" type="text" name="email"
maxlength="128" placeholder="Email" />
</div>
<div class="register-input">
<input id="register-password" type="password" name="password"
maxlength="128" placeholder="Password" />
</div>
<div class="register-input">
<input id="register-confirm-password" type="password"
name="confirmPassword" maxlength="128"
placeholder="Confirm Password" />
</div>
<input id="register-submit" type="submit" name="submit"
value="SIGN UP" class="register-button" />
</form>
<p class="form-message"></p>
</div>
</div>
<?php include "shared/_footer.php" ?>
<script src="javascript/register.js"></script>
</body>
</html>
There can be following issues when CSS is not being applied"
You have not included the CSS file (I don't see the file inclusion in your code)
You are applying it on an undefined ID or the class doesn't exist (Both of them can't be verified from your provided code).
The class name you are applying is wrong (In your case, you are applying '.input-error' if your class name starts with a '.', you need to escape it.)

Ajax login doesn't login when using the correct login user data

Hello I am totally new into Ajax. I have made a login with Ajax, but whenever I try to login, I get a message that the login didn't worked. I am looking for hours for the problem but can't find where I got wrong.
This is the body of the index.html
<div class="loginform-in">
<h1>User Login</h1>
<div class="err" id="add_err"></div>
<fieldset>
<form action="" method="post">
<ul>
<li> <label for="name">Username </label>
<input type="text" size="30" name="name" id="name" /></li>
<li> <label for="name">Password</label>w
<input type="password" size="30" name="word" id="word" /></li>
<li> <label></label>
<input type="submit" id="login" name="login" value="Login" class="loginbutton" ></li>
</ul>
</form>
</fieldset>
</div>
I didn't include the ajax code in another file. I did the code below in the head of the index.html
$(document).ready(function(){
$("#add_err").css('display', 'none', 'important');
$("#login").click(function(){
username=$("#name").val();
password=$("#word").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true') {
//$("#add_err").html("right username or password");
window.location="dashboard.php";
}
else {
$("#add_err").css('display', 'inline', 'important');
$("#add_err").html("<img src='images/alert.png' />Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").css('display', 'inline', 'important');
$("#add_err").html("<img src='images/ajax-loader.gif' /> Loading...")
}
});
return false;
});
});
And this is the login.php
require_once '../config.php';
session_start();
$uName = $_POST['name'];
$pWord = md5($_POST['pwd']);
$qry = "SELECT usrid, username, oauth FROM ajax WHERE username='".$uName."' AND pass='".$pWord."' AND status='active'";
$res = mysqli_query($mysqli, $qry);
$num_row = mysqli_num_rows($res);
$row=mysqli_fetch_assoc($res);
if( $num_row == 1 ) {
echo 'true';
$_SESSION['uName'] = $row['username'];
$_SESSION['oId'] = $row['orgid'];
$_SESSION['auth'] = $row['oauth'];
}
else {
echo 'false';
}
$.ajax({
type: "POST",
url: "login.php",
data: {name:username, pwd:password},
success: function(html){
if(html=='true') {
//$("#add_err").html("right username or password");
window.location="dashboard.php";
}
else {
$("#add_err").css('display', 'inline', 'important');
$("#add_err").html("<img src='images/alert.png' />Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").css('display', 'inline', 'important');
$("#add_err").html("<img src='images/ajax-loader.gif' /> Loading...")
}
});
Change data
Allow me to introduce you to the wonderful world of prepared statements using mysqli and pdo and also password_hash(); and password_verify() these will be answers to all your future problems, as #Chris85 have suggested. and since you are using the script on a live server u really need to use prepared statements.
First method PDO
<div class="loginform-in">
<h1>User Login</h1>
<div class="err" id="add_err"></div>
<fieldset>
<form action="" method="post" id="myform">
<ul>
<li> <label for="name">Username </label>
<input type="text" size="30" name="name" id="name" /></li>
<li> <label for="name">Password</label>w
<input type="password" size="30" name="word" id="word" /></li>
<li> <label></label>
<input type="submit" id="login" name="login" value="Login" class="loginbutton" ></li>
</ul>
</form>
</fieldset>
</div>
<script type="text/javascript">
$('document').ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
var formData = $('#myform').serialize();
$.ajax({
type : 'post',
url :'login.php',
data : formData,
dataType : 'json',
encode : true,
beforeSend : function(){
$("#add_err").html("<img src='images/ajax-loader.gif' /> Loading...");
},
success : function(result){
result = JSON.parse(result);
if(result == "ok"){
$("#add_err").html("right username or password");
setTimeout(' window.location.href = "dashboard.php"; ', 6000);
}else{
$("#add_err").html("<img src='images/alert.png' /> Wrong username or password");
}
}
});
});
});
</script>
config.php
<?php
$host = '127.0.0.1';
$db = 'YOURDATABASE';
$user = 'DBUSER';
$pass = 'YOURPASSWORD';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $opt);
?>
then login.php
<?php
session_start();
require 'config.php';
$message = '';
if (isset($_POST['login'])) {
$username = $_POST['name'];
$password = $_POST['word'];
try {
$stmt = $dbh->prepare("SELECT usrid,orgid, username,pass,oauth FROM ajax WHERE username= ? AND status='active'");
$stmt->execute([$username]);
$results = $stmt->fetchall();
if (count($results) > 0) {
//username is correct
foreach ($results as $key => $row) {
//verify password
if (password_verify($password, $row['pass'])) {
// password and username correct
$_SESSION['uName'] = $row['username'];
$_SESSION['oId'] = $row['orgid'];
$_SESSION['auth'] = $row['oauth'];
$message = 'ok';
} else {
//username and password does not match
$message = 'username and password does not match';
}
}
} else {
//username is incorrect
$message = 'incorrect user account';
}
}
catch (PDOException $e) {
error_log($e->getMessage());
}
echo json_encode($message);
}
?>
That's how simple is it is, so also on your registration page you will use prepared statements, read here how to insert data with prepared statements : https://phpdelusions.net/pdo#dml
also on the register page you no longer gonna use md5
so instead of $password = md5($_POST['word']); you will say
$password = $_post['word']; then u need to hash that password this
is how u will do it $hash=
password_hash($password,PASSWORD_DEFAULT); OR
'$hash=password_hash($_POST['word'],PASSWORD_DEFAULT);`
Before you can use this you need to make sure that you re register you account using password_hash();
2nd method mysqli prepared I'm not quit good with this one, i'm more comfortable with PDO, I might make mistakes somewhere, corrections a welcome as i'm also here to learn.
<?php
require 'config.php';
$message = '';
if (isset($_POST['submit'])) {
$username = $_POST['name'];
$password = $_POST['word'];
$stmt = $con->prepare("SELECT usrid, username,pass,orgid,oauth FROM ajax WHERE username= ? AND status='active'");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($user_id, $username,$pass,$orgid,$oauth);
$stmt->store_result();
if ($stmt->num_rows == 1) //username correct
{
while ($stmt->fetch()) {
if (passord_verify($password, $pass)) {
// correct username
$_SESSION['uName'] = $username;
$_SESSION['oId'] = $orgid
$_SESSION['auth'] = $oauth;
$message = 'ok';
} else {
$message = 'username and password does not match';
}
}
} else {
//username incorrect.
$message = 'incorrect user account';
}
echo json_encode($message);
$stmt->close();
$con->close();
}
on the second method use the current config that u have already.

Check if username is being used

I'm wondering if and how I could check if a username is being used.
I heard you can do this with jQuery but i just want something simple since I'm a beginner.
I have tried it but i can't seam to get it right. I just have it connected to a mysql database but since when a username with the same password as another account tries to logon, theres an issue, so i need this to stop people adding multiple usernames.
Here is my simple code for the registration form and the php
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
</div>
<?php
require('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
?>
For starters you don't want to just rely on something like unique field for doing this, of course you will want to add that attribute to your username column within your database but above that you want to have some sort of frontal protection above it and not rely on your database throwing an error upon INSERT INTO, you're also going to want to be using mysqli for all of this and not the old version, mysql. It's vulnerable to exploitation and no longer in common practice, here's what each of your files should look like:
connect.php
<?php
$conn = mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
register.php
<form action="insertuser.php" method="POST">
Username:
<input type="text" name="username" placeholder="Username" />
<br />
Password:
<input type="password" name="password" placeholder="Password" />
<br />
Name:
<input type="text" name="name" placeholder="Name" />
<br />
Email address:
<input type="text" name="email" placeholder="Email address" />
<br /><br />
<input type="submit" value="Register" />
</form>
<?php
// If there's an error
if (isset($_GET['error'])) {
$error = $_GET['error'];
if ($error == "usernametaken") {
echo "<h4>That username is taken!</h4>";
} elseif ($error == "inserterror") {
echo "<h4>Some kind of error occured with the insert!</h4>";
} else {
echo "<h4>An error occured!</h4>";
}
echo "<br />";
}
?>
Already have an account? Login here
insertuser.php
<?php
// Stop header errors
ob_start();
// Check if form has been posted
if (isset($_POST['username'])){
// Requre database connection file
require('connect.php');
// Clean the variables preventing SQL Injection attack
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
// Check if the username exists
// Construct SELECT query to do this
$sql = "SELECT id FROM user WHERE username = '".$username."';";
$result = mysqli_query($conn, $sql);
$rowsreturned = mysqli_num_rows($result);
// If the username already exists
if ($rowsreturned != 0) {
echo "Username exists, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=usernametaken');
} else {
// Construct the INSERT INTO query
$sql = "INSERT INTO user (username, password, email, name) VALUES ('".$username."', '".$password."', '".$email."', '".$username."');";
$result = mysqli_query($conn, $sql);
if($result){
// User was inserted
echo "User inserted!";
/* DO WHATEVER YOU WANT TO DO HERE */
} else {
// There was an error inserting
echo "Error inserting, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=inserterror');
}
}
}
?>
Good luck with whatever you're working on and I hope this helps!
James
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "select username from user where username = '$username'";
$res = mysql_query($query);
$rows = mysqli_num_rows($res);
if ($rows > 0) {
print 'Username already exists...';
} else {
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
}
Here is another example :) , succes.
<?php
//Set empty variables.
$usernameError = $emailError = $passwordError = $nameError = $okmsg = "";
$username = $password = $email = $name = "";
if (isset($_POST['submit'])) {
//Check if empty labels form
if (empty($_POST['name'])) {
$userError = "The 'name' is required.";
echo '<script>window.location="#registrer"</script>';
} else { $name = $_POST['name']; }
if (empty($_POST['email'])) {
$emailError = "El 'Email' es requerido.";
echo '<script>window.location="#registrer"</script>';
} else {
$email = $_POST['email'];
//Check only contain letters and whitespace.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "El 'Email' is not valid. ";
echo '<script>window.location="#registrer"</script>';
}
}
if (empty($_POST['password'])) {
$passwordError = "The 'password' is requiered.";
echo '<script>window.location="#registrer"</script>';
} else {
$password = $_POST['password'];
}
}
//Check if correctly filled
if ($name && $username && $email && $password) {
require('connect.php');
//Query SQL
$sql = "SELECT * FROM user WHERE username='$username'"; //String SQL
$query = mysqli_query($ConDB, $sql);//Query
//Securite
$username = mysqli_real_escape_string($ConDB, $username);
$password = mysqli_real_escape_string($ConDB, $username);
$passw = sha1($password);//For securite.
$name = mysqli_real_escape_string($ConDB, $username);
$email = mysqli_real_escape_string($ConDB, $username);
if ($existe = mysqli_fetch_object($query)) {
$usernameError = "The 'Username' is already exists.";
echo '<script>window.location="#registrer"</script>';
} else {
$sql = "INSERT INTO user (username, password, email, name) VALUES ('$username', '$passw', '$email', '$name')";
mysqli_query($ConDB, $sql);
$okmsg = "Register with succes.";
mysqli_close($ConDB);//Close conexion.
echo '<script>window.location="#registrer"</script>';
}
}
?>
<a name="registrer"></a>
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<?php echo $nameError; ?>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<?php echo $usernameError; ?>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<?php echo $emailError; ?>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<?php echo $passwordError; ?>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
<?php echo $okmsg; ?>
</form>
--
-- DATA BASE: `user`
--
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE user (
id int(11) unsigned not null auto_increment primary key,
name varchar(50) not null,
email varchar(80) not null unique,
username varchar(30) not null unique,
password varchar(40) not null
)engine=InnoDB default charset=utf8 collate=utf8_general_ci;
You can try use jQuery AJAX for what you want.
First, add this to your registration.php file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user submit the form
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
So now your registration.php file will look like this
registration.php
<form action="" method="POST">
<p>
<label>name : </label>
<input id="password" type="text" name="name" placeholder="name" />
</p>
<p>
<label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" />
</p>
<p>
<label>E-Mail : </label>
<input id="password" type="email" name="email"/>
</p>
<p>
<label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user typing in 'username' textbox
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
Then create php file named check_username.php to check the username submitted by user if it is already existed in database or still available.
check_username.php
<?php
// Check if 'username' textbox is not empty
if(!empty($_POST['username'])){
$username = trim(mysqli_real_escape_string($_POST['username']));
// Check the database if the username exists
$query = "SELECT username FROM `user` WHERE username = '".$username."'";
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0){
// if username already exist
// insert into array, to be sent to registration.php later
$response['status'] = 'exists';
}
else{
// if username available
$response['status'] = 'available';
}
}
header('Content-type: application/json');
echo json_encode($response);
exit;
?>
Here is how it works:
1. When user click the register button, jQuery will call check_username.php.
2. Now in check_username.php it will check the database if the username submitted already exists or still available.
3. Whatever the result either exists or available, check_username.php will send the result back to registration.php as string contains 'exists' or 'available'.
4. registration.php now get the result and will check the result sent by check_username.php if it contain 'exists' or 'available'. If the string is 'exists' then alert will be triggered. If the string is 'available', the form will be submitted.

JQuery POST only adding record to mysql once

I'm using JQuery to call a php script which will add a record to the mySQL database.
This works fine for the first time I try to add something, but if I want to add more records to the database, it will not add anything. There are no errors in the console or php error log. It does not work if I refresh or reopen the page either.
jquery:
$(document).ready(function(){
$("#myForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
var repassword = $("#repassword").val();
var email = $("#email").val();
var reemail = $("#reemail").val();
if(password != repassword)
{
alert("Passwords do not match");
return false;
}
else if(email != reemail)
{
alert("Emails do not match");
return false;
}
else {
$.post("signup_script.php",
{
username: username,
password: username,
email: email
});
}
});
});
php:
<?php
include_once('profile_Functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
createUser($username,$password,$email);
?>
html:
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>odd<span>job</span></div>
</div>
<br>
<div class="signup">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type = "text/javascript" src="js/js_functions.js"></script>
<form id ="myForm" action ="" method = "post" >
<input type="text" placeholder="username" id ="username" required = "required" maxlength = "15"><br>
<input type ="email" placeholder = "email" id = "email" required = "required" maxlength = "50"><br>
<input type ="email" placeholder = "re-enter email" id = "reemail" required = "required" maxlength = "50"><br>
<input type="password" placeholder="password" id="password" required = "required" pattern = "(?=.*\d)(?=.*[A-Z]).{10,}"><br>
<input type="password" placeholder="re-enter password" id ="repassword" required = "required"><br>
<p class = "passwordreq">Password must:</p>
<ol class = "passwordreq">
<li>Have 10 characters</li>
<li>Have one number</li>
<li>Have one uppercase letter</li>
</ol>
<input type="submit" value="sign up" id ="submit">
<input type="button" value="go back" onclick="window.location='index.html'">
</form>
insert function:
function setup(){
extract($_GET);
extract($_POST);
extract($_SERVER);
$host="localhost";
$user="root";
$passwd="";
$connect=mysql_connect($host,$user,$passwd) or die("error connecting mysql server");
mysql_select_db('oddjob',$connect) or die("error accessing db");
}
function createUser($name, $pass, $email){
setup();
$hashed_password = password_hash($pass, PASSWORD_DEFAULT);
$sql = "insert into profiles (UserName, Password, Email) values ('$name', '$hashed_password', '$email'); ";
$res = mysql_query($sql);
}
I wonder if the solution is related to this question: https://stackoverflow.com/a/6143475/652519.
Can you add the error function to your post function? Like so:
$.post("signup_script.php",
{
username: username,
password: username,
email: email
})
.error(function() { alert("error"); });
Then we can see if there are errors that happen upon insert in the DB.
You should close your connection each time
mysql_close($connect)

php to AJAX form submission

Newbie here in AJAX i got this code, Please help, my code keeps going to the sec_reg.php page even if the password is mismatch, or even when the form is valid, i want the user to stay on current page even if he submits a form. Here is my code
Here is my form
<h4>ADD ANOTHER ADMIN</h4>
<form action="sec_reg.php" method="post" name="registration_form">
<br>
<p>
<strong>Email</strong>
<br>
<br>
<input class="acc_input" type="text" id="email" name="email"placeholder="Email">
</p>
<br>
<p>
<strong> Password</strong>
<br>
<br>
<input class="acc_input" type="password" name="password" id="password" placeholder="Password">
<br /><br />
<strong> Confirm Password</strong>
<br>
<br>
<input class="acc_input" type="password" name="cpassword" id="cpassword" placeholder="Confirm Password">
<input type="hidden" name="p" id="p" value="">
<br>
</p>
<button type="submit" class="btnsubmit" onclick="formhash(this.form,
this.form.password, this.form.p);" ><strong>Register</strong></button>
</form>
Here is the script for forhash(the password needs to be hash before sending for security)
<script src="sha512.js"></script>
<script>
function formhash (form, password)
{
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("cpassword").value;
var ok = true;
if (password != cpassword) {
//alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("cpassword").style.borderColor = "#E34234";
ok = false;
}
else {
var p = document.createElement("input");
form.appendChild(p);
p.name="p";
p.type="hidden";
p.value=hex_sha512(password.value);
password.value="";
form.submit();
}
}
</script>
Here is my sec_reg.php
<?php
// Include database connection and functions here.
include '../Connections/mabini150_Conn.php';
if (isset($_POST['p']))
{
include 'login_Function.php';
// The hashed password from the form
$password = $_POST['p'];
// Create a random salt
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password (Careful with the chilli)
$password = hash('sha512', $password.$random_salt);
$username='nousername';
$email = $_POST['email'];
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)"))
{
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
$insert_stmt->execute();
You need to return false after the call to formhash(); in your onclick attribute.
<button type="submit" class="btnsubmit"
onclick="formhash(this.form, this.form.password, this.form.p); return false;" ><strong>Register</strong></button>
Otherwise the button will submit no matter what.

Categories