Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5

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


    Hello everyone,

    I'm back with another brain buster!

    This time, I'm checking the database using a PDO connection for a duplicate email address in a column, emailaddress. The problem is not in finding out if the e-mail address is a duplicate entry. The problem is displaying the error message to the user (not just seeing it in Firebug).

    All the other error messages this script detects are properly appended to a <p> element with an i.d. of errormessage. For some strange reason, this error goes unpublished and the form just sits there on submission. For example, if the user doesn't input a name, an error message will appear saying, "Please enter a name".

    Here's why I know the query and the detection of the duplicate entry is not the issue. I had set up the script to echo the variable, $dbCode, which is used to detect the results of the database writing. 3 corresponds to the e-mail being a duplicate (as you'll see), and that is what is being returned and echoed into Firebug/developer tools. Not only that, but the error message reads, "That e-mail address already exists", just like it should, as well as validation set to failure and database set to failure in my $response array that is sent back to JavaScript. Everything seems in place!

    confirmform.php (the file called by JavaScript):
    PHP Code:
    <?php
        $instance 
    = new CheckForm;
        
    $instance -> checkSubmission();
        
        class 
    CheckForm
        
    {
            public function 
    checkSubmission()
            {    
                
    $origEmail $_POST['origEmail'];
                
    $confirmEmail htmlspecialchars($_POST['confirmEmail']);
                
    $name htmlspecialchars($_POST['name']);
                
    $ageRange $_POST['age'];
                
    $gender $_POST['gender'];
                
    $country $_POST['country'];
                
    $catcher htmlspecialchars($_POST['catcher']);
                
    $mathAnswer htmlspecialchars($_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) {
                    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);
                    
                                   
    //I BELIEVE THIS IS WHERE THE PROBLEM IS
                    
    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);
            }
        }
    ?>
    databasewriter.php
    PHP Code:
    <?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_ERRMODEPDO::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();
                    echo 
    ' number of rows:     ' $number '    ';
                    if (
    $number 0){
                        return 
    3;
                    } else {
                        
    //echo $e -> getMessage();
                        
    return 2;
                    }
                }
                
    $connection NULL;
            }
        }
    ?>
    Many thanks for your support in this. I will continue to give back to the web dev. community

    -Tyler
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Jul 2003
    Posts
    3,232
    Rep Power
    593
    Off hand the data typing could be an issue. Although it looks correct to me, I'd lose the '===' and just use '==' to see if that works. Given that you control what is returned, I don't see any need for '===' in the first place.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5

    Unhappy No Luck


    Hi, gw1500se, and thanks for your reply.

    Unfortunately, using '==' instead of '===' did not solve the problem.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Jul 2003
    Posts
    3,232
    Rep Power
    593
    The you must be mistaken that the value of $dbCode is 3. Echo it just before that 'if' block again. It can't be 3.

    Comments on this post

    • etidd agrees : Not the solution, but I want to show my appreciation.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5

    Post It is 3.


    It is 3.

    Man, how frustrating can this be?!?

    PHP Code:
    /*
    ...
    ...
    */
    require_once('databasewriter.php');
                    
    $dbWriter = new DatabaseWriter;
                    
    $dbCode $dbWriter -> writeUserToDatabase($confirmEmail$name$ageRange$gender$country$category);
                    
                    echo 
    '    database code: ' $dbCode;
                    if (
    $dbCode === 1) {
                        
    $response['database'] = "pass";
                        echo 
    'Database Write Successful';
                    } else {
    /*
    ...
    */ 
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5
    Not only is it 3, but you'll notice in that if block that if $dbCode is 3, it will modify the message that is echoed back to JavaScript. The message about being a duplicate e-mail is even being returned, as well as setting validation to fail and database to fail.

    So, is there a problem with the JavaScript that is at the bottom of my website's HTML markup? Probably (definitely) not. The other errors are all being caught and displayed in the <p> element with the i.d. of errormessage, as the PHP is set up to catch in that long if block. BAFFLING.

    You can check for yourself here. Just use the forms beginning with the one on the bottom-right side.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Jul 2003
    Posts
    3,232
    Rep Power
    593
    Hold on. Is the PHP script echoing "That e-mail address already exists." or not? You did not show any javascript code but I have to presume you must be using Ajax. What are you getting back to the javascript?
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5
    Here is what exactly is being returned:

    category: number of rows: 1 database code: 3Database Write Failure

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

    Yes, I am using .ajax()
  16. #9
  17. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,540
    Rep Power
    2337
    So where's the JavaScript that's making this call and getting the return value? You've yet to show us this as far as I can see.
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5

    Question


    It is at the bottom of my index.html page, but here is the code in its entirety for all to see. There is a second .ajax() request near the bottom.

    Code:
    <script type="text/javascript"> 
           //This is for the #emailbox input field
    	$("#go").focus(function(){
    		if ($("#go").val() == $("#go").prop('defaultValue')){
    			$("#go").val('');
    		}
    	});
     
            //#emailbox input reset function
    	$("#go").on('focus blur', function(e) {
    	  var v = $(this).val()
    	  if (e.type == "focus"){
    		v = (v == "your e-mail")? "" : v;
    	  } else {
    		v = (v == "")? "your e-mail" : v;
    	  }
    	  $(this).val(v);
    	});
          
          //this is the function called by the success value of the first .ajax() call
          function testFirstResults(response){
            if (response.indexOf("Submission Successful") != -1){
    		  $("#blackoverlay").fadeIn(400);
              $("#submissionform").fadeIn(400);
            } else if (response.indexOf("Invalid E-mail") != -1){
              //alert("Invalid mail");
    		  $("#invalidemail").animate({"top": "+=36px"}, 700);
    		}
          }
    	  
              //THIS IS THE FUNCTION CALLED BY THE 2ND .AJAX() REQUEST TO HANDLE THE RESULTS
    	  function testSecondResults(data){
    	  	if (data['validation'] == "pass"){
    			$("#submissionform").css("display", "none");
    			$("#submitstatus p").append(data['message']);
    			$("#submitstatus").css("display", "block").delay(1400).fadeOut(800);
    			$("#blackoverlay").delay(1400).click(function(e){
    				$("#blackoverlay").remove();
    				$("#submitstatus").remove();
    			}).fadeOut(800);
    			$("#submitstatus h3").append("Submission Successful");
    			$("#emailbox input").each(function(){
                    $(this).prop("disabled", "disabled");
                });
    		} else {
    			$("#errormessage").empty().append(data['message']);
    		}
    	  }
    	  
    	  var mathAnswer = 0;
    	  var startTime = 0;
    	  var endTime = 0;
    	  var submissionTime;
    	  
              //this generates the math problem for spam catching
    	  function generateEquation(){
    	  	var num1 = Math.floor(Math.random() * 5) + 1;
    		var num2 = Math.floor(Math.random() * 5) + 1;
    		mathAnswer = num1 + num2;
    		$("#math").append("What is " + num1 + " + " + num2 + "?");
    	  }
    	  
          $(document).ready(function(){
    		
    		generateEquation();
    		
            $("#emailbox").submit(function(e){
    		  startTime = jQuery.now();
    		
              e.preventDefault();
              $.ajax({
                type: $(this).attr('method'),
                dataType: 'html',
                cache: false,
                url: "Scripts/emailtester.php",
                data: $(this).serialize(),
                success: function(data){
                  testFirstResults(data);
    			}
              });
            });
    		
                    //here is the .ajax request that pertains to the issue we are working on in this thread
    		$("#submissionform").submit(function(e){
    			var origEmail = $('#go').val();
    			var confirmEmail = $("#confirmemail").val();
    			var name = $("#name").val();
    			var age = $("#age").val();
    			var gender = $("#gender").val();
    			var country = $("#country").val();
    			var catcher = $("#aicatcher").val();
    			var addition = $("#addition").val();
    			endTime = jQuery.now();
    			submissionTime = endTime - startTime;
    			
    			e.preventDefault();
    		
    			$.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){
    				  testSecondResults(data);
    			  }
    			});
    		});
    		
    		$("#cancel").click(function(){
    			$("#blackoverlay").fadeOut(300);
    			$("#errormessage").empty();
    			$("#submissionform").fadeOut(300);
    		});
          });
    </script>
    Off topic, but can I post JavaScript code through JS tags?
  20. #11
  21. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,540
    Rep Power
    2337
    So if I understand you correctly, with this code:

    Code:
    //THIS IS THE FUNCTION CALLED BY THE 2ND .AJAX() REQUEST TO HANDLE THE RESULTS
    	  function testSecondResults(data){
    	  	if (data['validation'] == "pass"){
    			$("#submissionform").css("display", "none");
    			$("#submitstatus p").append(data['message']);
    			$("#submitstatus").css("display", "block").delay(1400).fadeOut(800);
    			$("#blackoverlay").delay(1400).click(function(e){
    				$("#blackoverlay").remove();
    				$("#submitstatus").remove();
    			}).fadeOut(800);
    			$("#submitstatus h3").append("Submission Successful");
    			$("#emailbox input").each(function(){
                    $(this).prop("disabled", "disabled");
                });
    		} else {
    			$("#errormessage").empty().append(data['message']);
    		}
    	  }
    either you're not entering the else or you are and the message is not being displayed? If that's the case, you're using Firebug, so set a breakpoint on this line
    Code:
    	  	if (data['validation'] == "pass"){
    and step through the code. If you are getting into your else, then I would suggest that perhaps your element with the errormessage id is set to display:none or something in your CSS.
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5

    Exclamation testSecondResults() function not running


    So, I seem to think now that the entire testSecondResults() function is not running at all. I put that console log statement along with an alert with a bunch of gibberish just so I would know if it is running- it is not appearing after I submit the form; hence, it's not running. I'm not getting anything new back returned into the console that I haven't seen already.

    database code: 3 Database Write Failure {"validation":"fail","message":"That e-mail address already exists.","database":"fail"}
    Code:
    	  function testSecondResults(data){
    		alert('blah blah blah blah blah blah blah');
    	  	console.log(data);
    		if (data['validation'] == "pass"){
    			$("#submissionform").css("display", "none");
    			$("#submitstatus p").append(data['message']);
    			$("#submitstatus").css("display", "block").delay(1400).fadeOut(800);
    			$("#blackoverlay").delay(1400).click(function(e){
    				$("#blackoverlay").remove();
    				$("#submitstatus").remove();
    			}).fadeOut(800);
    			$("#submitstatus h3").append("Submission Successful");
    			$("#emailbox input").each(function(){
                    $(this).prop("disabled", "disabled");
                });
    		} else {
    			$("#errormessage").empty().append(data['message']);
    		}
    	  }
    I had a hunch that this was the case since it's been a long time since I saw the successful submission animation run if the submission was valid and database writing worked.
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5

    Unhappy Very Strange Behavior


    If I submit a valid entry, it doesn't display the success message and all the other things if it is a valid submission, but if I fill out the form with invalid info, the alert message will pop up and the error message displayed.
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Location
    Atlanta, GA, USA (unfortunately)
    Posts
    59
    Rep Power
    5
    I did what you said about setting a breakpoint in Chrome Developer Tools. I didn't know what to do once I set the breakpoint on that line as when I tried to fill out the form, nothing seemed to happen once I reached the point that the if statement would evaluate the validation index for pass or failure. So I right clicked the line and chose "Evaluate in console". Here's what that returned: SyntaxError: Unexpected end of input
  28. #15
  29. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Jul 2003
    Posts
    3,232
    Rep Power
    593
    It sounds like maybe this should now be moved to the Javascript forum.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo