Reputation: 569
I've been testing my register, and to an extent the code works. But it seems to not be able to compare the text from the PHP script.
I tried using existing email AND username, existing email, existing username and two non-existing username and email. But all give me the echoed data + Fail (which is the end conditional statement in JQuery).
JQuery:
$( function ajaxRegCheck() {
$('#reg_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'save_register.php',
data: $(this).serialize(),
success: function(data)
{
if(data == "un_em_exists"){
alert(data+" Username and Email exists.");
} else if(data == "un_exists") {
alert(data+" Username exists.");
} else if(data == "em_exists") {
alert(data+" Email exists.");
} else if(data == "success"){
alert(data+" Created account.");
} else {
alert(data+ " Fail.");
}
}
});
});
});
PHP Register:
if(($exist_check_user->rowCount() > 0) AND ($exist_check_em->rowCount() > 0)){
echo "un_em_exists";
} else if($exist_check_user->rowCount() > 0) {
echo "un_exists";
} else if($exist_check_em->rowCount() > 0) {
echo "em_exists";
} else {
$sql = "INSERT INTO Users (username, email, password) VALUES (:r_un, :r_em, :r_pw)";
$q = $cdb->prepare($sql);
$q->execute(array(':r_un'=>$reg_username,':r_em'=>$reg_email,':r_pw'=>$reg_pw));
echo "success";
}
I do not why it skips the if statements in the JQuery and go straight to the last else condition. It clearly outputs the string from the PHP side correctly, but it doesn't seem to be able to compare the string?
For example, if I register with existing username and email, it'll echo 'un_em_exists' response. On the JQuery the alert matches this as it says, "un_em_exists Fail.", which is the last statement.
UPDATE:
Found the problem, but not too sure how to fix. I tested the string length, and in return I get string length 16 (testing from the JQuery side), and on PHP I get 12 - which is the correct amount for "un_em_exists".
I do not know what the extra 4 amounts come from though.
Upvotes: 1
Views: 911
Reputation: 114
After success trim your data by using data.trim(), might be there is whitespace
Upvotes: 1
Reputation: 1438
Make sure the returned value is text like so:
$( function ajaxRegCheck() {
$('#reg_form').submit(function(e) {
e.preventDefault();
$.ajax({
dataType: 'text',
type: "POST",
url: 'save_register.php',
data: $(this).serialize(),
success: function(data)
{
if(data == "un_em_exists"){
alert(data+" Username and Email exists.");
} else if(data == "un_exists") {
alert(data+" Username exists.");
} else if(data == "em_exists") {
alert(data+" Email exists.");
} else if(data == "success"){
alert(data+" Created account.");
} else {
alert(data+ " Fail.");
}
}
});
});
});
Upvotes: 0