Basically, I am validating a sign-up form and calling a php script with ajax to check if an email address already exists or else the query executes. If an email address already exists (checked with a count query), I am echoing an error back to the ajax function (via response) - however it is not being read.
I tried researching similar topics but no luck.
ajax
$.ajax({
type: 'POST',
url: 'signup-user.php',
dataType: 'text',
data: $('form').serialize(),
success: function(response) {
if(response == "error-email-exists"){
$('#errorMsg').html("An account is already assosciated with the email adress you entered.");
$('#errorMsg').hide().stop(true,true).fadeIn(600);
}else if(response == "success"){
window.location = "index.php";
}else{
$('#errorMsg').html(response);
$('#errorMsg').hide().stop(true,true).fadeIn(600);
}
}
});
php
<?php
session_start();
include("conn.php");
$post_firstName = $_POST['firstName'];
$post_lastName = $_POST['lastName'];
$post_dateofBirth = $_POST['dateofBirth'];
$post_gender = $_POST['gender'];
$post_propertyNo = $_POST['propertyNo'];
$post_propertyAddress = $_POST['propertyAddress'];
$post_streetAddress = $_POST['streetAddress'];
$post_locality = $_POST['locality'];
$post_email = $_POST['email'];
$post_password = $_POST['password'];
$checkexistsQuery = $conn->prepare('SELECT count(*) AS countExists FROM tbl_account acc WHERE acc.email = ?');
$checkexistsQuery->bind_param('s', $post_email);
$checkexistsQuery->execute();
$checkexistsQuery->store_result();
$checkexistsQuery->bind_result($countExists);
$checkexistsQuery->fetch();
if($countExists > 0){
echo 'error-email-exists';
}else{
$signupQuery = $conn->prepare('insert into tbl_account (name, surname, email, password, dob, genderID, propertyNumber, propertyAddress, streetAddress, localityID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$signupQuery->bind_param('ssssssssss', $post_firstName,$post_lastName,$post_dateofBirth,$post_gender,$post_propertyNo,$post_propertyAddress,$post_streetAddress,$post_locality,$post_email,$post_password);
if($signupQuery->execute()){
echo 'success';
}else{
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
}
?>
The problem is that 'error-email-exists' and 'success' messages are not being read.
<?phpthen some datas are sent before anything (and the response will be different than'error-email-exists'console.log(response)?successblock anerror: function(error) { console.log(error)}block to be suresuccessis entered.response == "error-email-exists"check. It's for this reason it's much better practice to return a serialised response format. A quick fix would beresponse.trim() === 'error-email-exists', however I'd suggest using JSON instead to avoid the problem entirely.