I am trying to check if the username exists in my mysql database and if it does, php side does that check and echo backs "duplicate" which should then be recieved by ajax. However it is not recieving and when I try to do output on my developer tools, i get that front end value as undefined.
Here is my jquery ajax part:-
$("#create").click(function(e){
e.preventDefault();
$.ajax({
type:'post',
url:'usernameTest.php',
data: {usr: $("#usr").val(),
pwd: CryptoJS.MD5($("#pwd").val()).toString()
},
success: function(data){
//console.log(data);
if(data == "duplicate"){
$("#userErrorDiv").html("User already exists. Please enter another one").css("color","red");
console.log("duplicate data");
}
else{
console.log("data not duplicate:"+data);
}
},
error(err){
console.log("error "+err);
}
});
Here is the php part:-
<?php
function recieveFormData()
{
if (isset($_POST['usr'], $_POST['pwd'])) {
global $connection;
global $username;
global $password;
$username = $_POST['usr'];
$password = $_POST['pwd'];
}
}
/*do insertion if username not found */
function insertIntoTable($username, $password){
global $connection;
$query="INSERT INTO users(username, password) VALUES('$username','$password')";
$result=mysqli_query($connection,$query);
if(!$result){
die("Sorry. Query failed to execute ".mysqli_error());
}
}
function connectToDatabase(){
global $connection,$username;
$connection=mysqli_connect("localhost","root","","usermanagement");
if(!$connection){
echo "Sorry! Cannot connect to the database";
}
}
function readFromDatabase(){
global $connection,$username;
$query="SELECT * from users where username='$username'";
$result=mysqli_query($connection,$query);
if(!$result){
die("query error");
}
if(mysqli_num_rows($result)!=0) {
echo "duplicate";
//return false;
}
else{
while($row = mysqli_fetch_assoc($result)) {
$usernameFromTable=$row['username'];
// print_r($usernameFromTable);
echo "<tr><td>".$usernameFromTable."</td><td>User</td><td></td></tr>";
}
}
//return true;
}
recieveFormData();
connectToDatabase();
readFromDatabase();
?>
And this is the simple html im using:-
<label for="usr">Username</label>
<input type="text" name="usr" id="usr">
<label for="pwd">Password</label>
<input type="password" name="pwd" id="pwd">
<button id="create" class="create" type="submit" name="create">Create</button>
<div id="userErrorDiv"></div>