Script Captures Duplicate E-mail Entry in Database, but Doesn't Display User-end Msg

I get this:

All GoodDatabase Write Failure{“validation”:“fail”,“message”:“That e-mail address already exists.”,“database”:“fail”}

OK, that doesn’t make much sense.

Can you post the entire PHP script please, including any dependencies.

confirmform.php


<?php
	$instance = new CheckForm;
	$instance -> checkSubmission();
	
	class CheckForm
	{
		public function checkSubmission()
		{	
			$origEmail = $_POST['origEmail'];
			$confirmEmail = strip_tags($_POST['confirmEmail']);
			$name = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['name']))))));
			$ageRange = $_POST['age'];
			$gender = $_POST['gender'];
			$country = $_POST['country'];
			$catcher = strip_tags($_POST['catcher']);
			$mathAnswer = strip_tags($_POST['addition']);
			$rightAnswer = $_POST['mathAnswer'];
			$submissionTime = $_POST['submissionTime'];
			$status = 0;
		
			$response = array("validation" => " ", "message" => " ", "database" => " ");
			
			if (empty($confirmEmail) && empty($name) && $country == "Select Country") {
				$response['message'] = "That's not a valid submission.";
			} elseif (empty($confirmEmail) && $country == "Select Country"){
				$response['message'] = "Please confirm your e-mail and select a location.";
			} elseif (empty($name) && $country == "Select Country"){
				$response['message'] = "Please enter a name and select a location.";
			} elseif (empty($name)) {
				$response['message'] = "Please enter a name.";
			} elseif (empty($confirmEmail)) {
				$response['message'] = "No confirmation e-mail was entered.";
			} elseif ($origEmail != $confirmEmail) {
				$response['message'] = "E-mail addresses don't match.";
			} elseif ($country == "Select Country") {
				$response['message'] = "Please select a location.";
			} elseif ($mathAnswer != $rightAnswer) {
				$response['message'] = "Math answer is incorrect.";
			} elseif (!empty($catcher)) {
				$response['message'] = "Bot submission.";
			} elseif ($submissionTime <= 8000) {
				$response['message'] = "Woah! Slow down and fill out the form.";
			} else
				$status = 1;
				
			if ($gender == "Male")
				$gender = "M";
			elseif ($gender == "Female")
				$gender = "F";
			else
				$gender = NULL;

			
			if ($status == 1) {
			  echo "All Good";
			  require_once("categoryfinder.php");
			  $categoryFinder = new CategoryFinder;
			  $category = $categoryFinder -> getCategory();
							
			  $response['validation'] = "pass";
			  $response['message'] = "Thanks for joining the e-mail list, <b>" . $name . "</b>, under the e-mail address, <b>" . $confirmEmail . "</b>.";
									
			  require_once('databasewriter.php');
			  $dbWriter = new DatabaseWriter;
			  $dbCode = $dbWriter -> writeUserToDatabase($confirmEmail, $name, $ageRange, $gender, $country, $category);
			
			  if ($dbCode == 1) {
				$response['database'] = "pass";
				echo 'Database Write Successful';
			  } else {
				$response['database'] = "fail";
				$response['validation'] = "fail";
				echo 'Database Write Failure';
			  }
			
			  if ($dbCode == 2) {
				$response['message'] = "Server error. Please try again later.";
			  } elseif ($dbCode == 3) {
				$response['message'] = "That e-mail address already exists.";
			  }
			
			  echo json_encode($response);
			}
		}
	}
?>

categoryfinder.php


<?php
	class CategoryFinder
	{
		public function getCategory() {
			$currentURL = $_SERVER['HTTP_REFERER'];
			
			// Build the match to array
			$matchTo = array(
				'worldreviewgroup'  => 'Home Page',
				'health'    => 'Health',
				'insurance' => 'Insurance',
				'general'   => 'General',
				'dating'    => 'Dating',
				'education' => 'Education',
				'legal'     => 'Legal',
				'startyour' => 'Business Opportunities',
				'business'  => 'Business Services'
			);
			
			foreach($matchTo AS $key => $value) {
				if(strpos($currentURL, $key) !== FALSE) {
					return $value;
					break;
				}
			}
			
			return ' ';
		}
	}
?>

databasewriter.php


<?php
	class DatabaseWriter
	{
		public function writeUserToDatabase($email , $name , $age , $gender , $country , $category)
		{	
			$host = '*************';
			$dbname = 'emailcollection';
			$user = '**********';
			$pass = '*********';
			
			$connection = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $user, $pass);
			
			try {
				$connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$statement = $connection -> prepare("INSERT INTO emailcollection (emailaddress, name, age, gender, country, category) VALUES (:emailaddress, :name, :age, :gender, :country, :category)");
				$statement -> bindValue(':emailaddress', $email);
				$statement -> bindValue(':name', $name);
				$statement -> bindValue(':age', $age);
				$statement -> bindValue(':gender', $gender);
				$statement -> bindValue(':country', $country);
				$statement -> bindValue(':category', $category);
				$statement -> execute();
		
				return 1;
			}catch (PDOException $e){
				$dupeQuery = $connection -> prepare("SELECT * FROM emailcollection WHERE emailaddress = '" . $email . "'");
				$dupeQuery -> execute();
				$number = $dupeQuery -> rowCount();
				if ($number > 0){
					return 3;
				} else {
					echo $e -> getMessage();
					return 2;
				}
			}
			$connection = NULL;
		}
	}
?>

Ah ok, I meant to remove the other code completely, not just add the line echo "All Good".

Could you change confirmform.php to this:

<?php
    $instance = new CheckForm;
    $instance -> checkSubmission();

    class CheckForm
    {
        public function checkSubmission()
        {
            $origEmail = $_POST['origEmail'];
            $confirmEmail = strip_tags($_POST['confirmEmail']);
            $name = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['name']))))));
            $ageRange = $_POST['age'];
            $gender = $_POST['gender'];
            $country = $_POST['country'];
            $catcher = strip_tags($_POST['catcher']);
            $mathAnswer = strip_tags($_POST['addition']);
            $rightAnswer = $_POST['mathAnswer'];
            $submissionTime = $_POST['submissionTime'];
            $status = 0;

            $response = array("validation" => " ", "message" => " ", "database" => " ");

            if (empty($confirmEmail) && empty($name) && $country == "Select Country") {
                $response['message'] = "That's not a valid submission.";
            } elseif (empty($confirmEmail) && $country == "Select Country"){
                $response['message'] = "Please confirm your e-mail and select a location.";
            } elseif (empty($name) && $country == "Select Country"){
                $response['message'] = "Please enter a name and select a location.";
            } elseif (empty($name)) {
                $response['message'] = "Please enter a name.";
            } elseif (empty($confirmEmail)) {
                $response['message'] = "No confirmation e-mail was entered.";
            } elseif ($origEmail != $confirmEmail) {
                $response['message'] = "E-mail addresses don't match.";
            } elseif ($country == "Select Country") {
                $response['message'] = "Please select a location.";
            } elseif ($mathAnswer != $rightAnswer) {
                $response['message'] = "Math answer is incorrect.";
            } elseif (!empty($catcher)) {
                $response['message'] = "Bot submission.";
            } elseif ($submissionTime <= 8000) {
                $response['message'] = "Woah! Slow down and fill out the form.";
            } else
                $status = 1;

            if ($gender == "Male")
                $gender = "M";
            elseif ($gender == "Female")
                $gender = "F";
            else
                $gender = NULL;

            if ($status == 1) {
              echo "All Good";
            }
        }
    }
?>

Then submit the form with valid data and tell me what you see on the console.

It should just hopefully be the words “All Good”

I see what was expected, the words ‘All Good’. Nothing else.

Edit: plus the parseError from the JS ajax request

Cool!

Now we’ve got to start putting bits back in until we find out what is causing the error.

Change this:

if ($status == 1) {  
  echo "All Good"
}

to this:

if ($status == 1) {  
  require_once("categoryfinder.php");  
  $categoryFinder = new CategoryFinder;  
  $category = $categoryFinder -> getCategory();  
                  
  $response['validation'] = "pass";  
  $response['message'] = "Thanks for joining the e-mail list, <b>" . $name . "</b>, under the e-mail address, <b>" . $confirmEmail . "</b>.";
  
  echo json_encode($response);
}

What do you see on the console?

I don’t think we have gotten down to a successful AJAX call. I still see the same error message that is being thrown by the error block of that AJAX call.

What I am seeing now in the console is:

All Good{“validation”:“pass”,“message”:“Thanks for joining the e-mail list, <b>Tyler<\/b>, under the e-mail address, <b>etidd88@ymail.com<\/b>.”,“database”:" "}

We have, as before you wrote:

This is also backed up by the fact that we are seeing all of this in the success callback.

Just to be sure however, can you remove the error callback from the JavaScript, like so:

$.ajax({
  type: "POST",
  dataType: 'json',
  cache: false,
  url: "Scripts/confirmform.php",
  data: { 
  origEmail: origEmail,
  confirmEmail: confirmEmail,
  name: name,
  age: age,
  gender: gender,
  country: country,
  catcher: catcher,
  addition: addition,
  mathAnswer: mathAnswer,
  submissionTime: submissionTime 
  },
  success: function(data) {
    console.log(data);
  }
});

and confirm that you are still seeing the same results.

I really don’t think it’s working properly, seeing as I still have a call to the other function that shows/hides the forms, displays a success message in the #submitstatus div, and fades out. I’m seeing none of that anymore, even with a valid submit.

			  success: function(data) {
				alert("success");
				console.log(data);
				testSecondResults(data);
			  },

To add to that, I’m not seeing an alert message saying ‘success’.

I did what you said, anyhow, and removed the error callback and I am seeing the same results:

All Good{“validation”:“pass”,“message”:“Thanks for joining the e-mail list, <b>Tyler<\/b>, under the e-mail address, <b>etidd88@ymail.com<\/b>.”,“database”:" "}

:slight_smile:

We first have to work out what’s going wrong in the PHP code as, as we established previously, upon a valid form submission, it cannot encode the string it is handed as JSON.
Once we solve that, the rest should follow quite easily.
At least that’s the theory …

OK, try changing your PHP code to this and let me know what gets logged to the console.

if ($status == 1) {  
  require_once("categoryfinder.php");  
  $categoryFinder = new CategoryFinder;  
  $category = $categoryFinder -> getCategory();  
        
  $response['validation'] = "pass";  
  $response['message'] = "Thanks for joining the e-mail list, <b>" . $name . "</b>, under the e-mail address, <b>" . $confirmEmail . "</b>.";  
                
  require_once('databasewriter.php');  
  $dbWriter = new DatabaseWriter;  
  $dbCode = $dbWriter -> writeUserToDatabase($confirmEmail, $name, $ageRange, $gender, $country, $category);  
  
  if ($dbCode == 1) {  
    $response['database'] = "pass";  
  } else {  
    $response['database'] = "fail";  
    $response['validation'] = "fail";  
  }  
  
  echo json_encode($response);  
}

The console says:

All Good{“validation”:“fail”,“message”:“Thanks for joining the e-mail list, <b>Tyler<\/b>, under the e-mail address, <b>etidd88@ymail.com<\/b>.”,“database”:“fail”}

I’m sure the database writing failed because I already have wrote that e-mail address in there before. That doesn’t matter in this case, though. I know the database script is fine.

Hi,

It shouldn’t say “All Good”, as I removed that from the PHP a few posts back.

Nonetheless, we’re a step forward, so let’s add the final bit back in:

if ($status == 1) {
  require_once("categoryfinder.php");
  $categoryFinder = new CategoryFinder;
  $category = $categoryFinder -> getCategory();

  $response['validation'] = "pass";
  $response['message'] = "Thanks for joining the e-mail list, <b>" . $name . "</b>, under the e-mail address, <b>" . $confirmEmail . "</b>.";

  require_once('databasewriter.php');
  $dbWriter = new DatabaseWriter;
  $dbCode = $dbWriter -> writeUserToDatabase($confirmEmail, $name, $ageRange, $gender, $country, $category);

  if ($dbCode == 1) {
    $response['database'] = "pass";
  } else {
    $response['database'] = "fail";
    $response['validation'] = "fail";
  }

  if ($dbCode == 2) {
    $response['message'] = "Server error. Please try again later.";
  } elseif ($dbCode == 3) {
    $response['message'] = "That e-mail address already exists.";
  }

  echo json_encode($response);
}

What does that give you on the console?

Well, I’ll be darned! :eek: It worked! :vinnie:

The console says:

{“validation”:“fail”,“message”:“That e-mail address already exists.”,“database”:“fail”}

Not only that, but the ajax request gave me the success message, and the message was posted to the <p> element with the i.d. of #errormessage just like I want it to.

How?! I don’t know how anything was changed that much. This obviously shows the power of stepping through the code bit by bit. I’m at a loss to explain the fix, however, because I don’t know what’s really any different than what was originally coded.

Ah-ha. The solution is that the extra echo statements I had in the script that said “Database Write Successful” or “Database Write Failure” were causing a problem.

Excellent. Well done!

The only thing I altered about the original PHP code, was that I removed the echo statements, e.g.:

echo 'Database Write Successful';

This is probably what was causing the error. This is something you can check.

Edit: You were quicker. Great minds think alike :slight_smile:

Also, don’t get confused with the success and error callbacks.

If you submit your form with invalid data and the PHP script spits a “validation failed” message back at you, this is still a successful AJAX call.

The error callback would be more for the case that your PHP script falls over and dies due to a syntax error (or something similar) and that the AJAX call cannot complete successfully.

Well, thank you as always, Dave.

I certainly could not have gotten as far as I have without these forums & the books I have gotten from SitePoint.

I’m getting so close to completing this project, moving on to the next one, and using this project in internet marketing campaigns.

I’ve tried to help people on the forums like this before, but I’m not nearly experienced enough to help people along.

You’re welcome.

Don’t think that!
Just hang around the place and sooner or later you’ll see a question where you think “Hey, I can answer that”.
Then you’ll see another, and another, and so on …
Don’t underestimate your own knowledge.

Also, there are loads of less technical forums here, such as the Community Center or [URL=“http://www.sitepoint.com/forums/forumdisplay.php?240-Content”]Content.

:slight_smile: