jquery php form process

I have the following php file that process a email address in a form.  But the problem is none of the errors are displaying to the user.  If the user enters a invalid email address no message is coming up any ideas as to why.
HTML Document---------------------------------------------------------------------------------------------------------------
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MYtitle</title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
    	$(document).ready(function(){ 
    			// Email Signup
    			$("form#newsletter").submit(function() {	
    				var dataStr = $("#newsletter").serialize();
    				//alert(dataStr);
    					$.ajax({
    						type: "POST",
    						url: "process.php",
    						data: dataStr,
    						success: function(del){
    							$('form#newsletter').hide();
    							$('#signup-success').fadeIn();
    						}
    				});
    			return false;
    			});				
    	}); 
</script>
<style type="text/css">
 
body
{
font-family:Arial, Helvetica, sans-serif;
background-color:#000000;
color:#FFFFFF;
 
}
 
#content
{
  width:379px;
  margin:0 auto;
}
 
#content #email {
	margin-right:2px;
	padding:5px;
	width:145px;
	border-top:1px solid #ccc;
	border-left:1px solid #ccc;
	border-right:1px solid #eee;
	border-bottom:1px solid #eee;
	font-size:14px;
	color:#9e9e9e;
}
#content #signup-success {
	margin-bottom:20px;
	padding-bottom:10px;
	display:none;
}
#content #signup-success p, #signup-success-nojs {
	padding:5px;
	background:#fff;
	border:1px solid #dedede;
	text-align:center;
	font-weight:bold;
	color:#DE2025;
}
</style>
</head>
<body>
 
<div id='content'>
<?php include('process.php'); ?>
 
<img src="images/info.jpg" alt"New site" width="379" height="327" />
<form id="newsletter" class="divider" name="newsletter" method="post" action="" style="margin-top:5px;">
  Enter your email address 
  <input id="email" type="text" name="email" />
  <input id="submit-button" type="image" src="images/submit.gif" alt="Get Updated" style="padding-top:5px;" />
  <input id="submitted" type="hidden" name="submitted" value="true"  />
</form>
<div id="signup-success">
  <p>Thank you We will notify you!</p>
</div>
</div>
</body>
</html>
-----------------------------------------------------------------------------------------------------------------------------------
 
 
 
-----------------------------------------------------------------------------------------------------------------------------------
Here is the php file called process.php
-----------------------------------------------------------------------------------------------------------------------------------
<?php
        // DB info
        $dbhost = 'mydomain.com';
        $dbuser = 'username'; 
        $dbpass = 'pass';
        $dbname = 'mydb';
 
        // Open connection to db
        $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
        mysql_select_db($dbname);
 
        // Form variables
        $email 		= $_POST['email'];
        $submitted	= $_POST['submitted'];
 
        // Clean up
        function cleanData($str) {
        	$str = trim($str);
        	$str = strip_tags($str);
        	$str = strtolower($str);
        	return $str;
        }
        $email 	= cleanData($email);
 
        $error = "";
        if(isset($submitted)) 
		{
        	if($email == '')
			 {
        		$error .= '<p class="error">Please enter your email address.</p>' . "\n";
        	} 
			  else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", $email)) {
        		$error .= '<p class="error">Thank you We will notify you once we go live!</p>' . "\n";
        	}
        	if(!$error){
        		echo '<p id="signup-success-nojs">Thank you We will notify you once we go live!</p>';
 
        		// Add to database
        		$add_email  = "INSERT INTO bulk_mailing (email,groupid) VALUES ('$email',15)";
        		mysql_query($add_email) or die(mysql_error());
 
        	}else{
        		echo $error;
        	}
        }
    ?>
 
-----------------------------------------------------------------------------------------------------------------------------------
Here is the END process.php
-----------------------------------------------------------------------------------------------------------------------------------

Open in new window

stargateatlantisAsked:
Who is Participating?
 
alien109Connect With a Mentor Commented:
FYI, I can't test that code, so there may be some slight tweaks that need to be made. But the logic is sound.
0
 
alien109Commented:
you're returning an error string from the ajax call, but not doing anything with it in your callback.

success: function(del){
    // need to do something with the response here to display message returned!
    alert(del)
    $('form#newsletter').hide();
    $('#signup-success').fadeIn();
}

also - why are you including the process.php file directly in your html page? right now, it executes when the page loads. I think you'd want it to only execute during the ajax call.
0
 
stargateatlantisAuthor Commented:
I took out the php directly in my HTML page.  I can't remember what I was thinking.  Also where do I put the success function so that if a user enters invalid data the fade in screen will notify the user.
0
 
alien109Commented:
The success function executes if the post request (the ajax call) was successful, regardless of the validation of the email.

What you'll need to do, is return not only a message from the php script, but some indication of the success/fail state of the email validation.

If you only returned a message from the PHP script on failure, you could check the value of "del" variable which is the argument to the success function. This is what will hold the string returned from the PHP script. If it's not an empty string or not null, then you know you have an error and you display that. Otherwise, you display the success messages.

But, since you are returning messages for both success and failure, you'll need to indicate in the return value if there was success or is there was an error. One way to do this would be to use a more complex datatype for the return and use json.

To implement the second method, you'll need to modify your javascript and your php script.

First, in PHP, change your script as follows:

<?php
        // DB info
        $dbhost = 'mydomain.com';
        $dbuser = 'username';
        $dbpass = 'pass';
        $dbname = 'mydb';
 
        // Open connection to db
        $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
        mysql_select_db($dbname);
 
        // Form variables
        $email             = $_POST['email'];
        $submitted      = $_POST['submitted'];
 
        // Clean up
        function cleanData($str) {
              $str = trim($str);
              $str = strip_tags($str);
              $str = strtolower($str);
              return $str;
        }
        $email       = cleanData($email);
 
      $response = array();

      if(isset($submitted))
      {
            if($email == '')
            {
                  $response["success"] = false;
                  $response["message"] = '<p class="error">Please enter your email address.</p>';

            }
            else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", $email))
            {
                  $response["success"] = true;
                  $response["message"] = '<p class="error">Thank you We will notify you once we go live!</p>';
                  // Add to database
                  $add_email  = "INSERT INTO bulk_mailing (email,groupid) VALUES ('$email',15)";
                  mysql_query($add_email) or die(mysql_error());
            }
            echo json_encode($response);
      }
?>

That will return a json string with the message and a success boolean variable.

Then you'll need to change your javascript to something like:

$.ajax({
      type: "POST",
      url: "process.php",
      data: dataStr,
      dataType, "json",
      success: function(del)
      {
            if(del.success === true)
            {
                  // Display success message (del.messages has the value returned from PHP)
                  $('form#newsletter').hide();
                  $('#signup-success').fadeIn();
            }
            else if(del.success === false)
            {
                  // Display error message (del.messages has the value returned from PHP)
            }
      }
});

You'll need to change what happens for success or failure so that it does what you want, but the structure is there!


0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.