Solved

php form - on submit the form disappear and the success shows

Posted on 2013-06-27
5
2,019 Views
Last Modified: 2013-06-27
I have a php form that when a user submits, the errors/success response shows on the same page.

If a user does not enter the required fields ( name, email, message ) an error shows in the #response div above the form. That works great!

If a user fills out the form and submits it, the Success field shows in the #response div as well, but the form still shows visible.

Question:
Is there a way to have the Form is visible when errors show in the #response div
but
the Form is hidden when Success shows in the #response div?

Thanks for your help!

I have included my code below:

contact.html
<!DOCTYPE HTML>
<html>
  <head>
    <title>Contact Form</title>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$('#contactform').submit(function(e) {
		e.preventDefault();
		
		var url = $(this).attr('action');
		var data = $(this).serialize();
		
		$.post(url, data)
			.done( function(response) {
				$('#response').html(response);
			})
			.fail( function() {
				alert("The AJAX request failed!");
			});
	});
});
</script>
<style>
#response{ font-family:Arial, Helvetica, sans-serif;color:#0000FF;font-size:16px;}
</style>
  </head>
  <body>
  
  
    <div id="wrap">
      <div id="response"></div>
    
      <form id="contactform" action="processForm.php" method="post">
        <table>
          <tr>
            <td><label for="name">Name:</label></td>
            <td><input type="text" id="name" name="name" /></td>
          </tr>
          <tr>
            <td><label for="email">Email:</label></td>
            <td><input type="text" id="email" name="email" /></td>
          </tr>
          <tr>
            <td><label for="message">Message:</label></td>
            <td><textarea id="message" name="message" rows="5" cols="20"></textarea></td>
          </tr>
          <tr>
            <td></td>
            <td><input type="submit" value="Send!" id="send" /></td>
          </tr>
        </table>
      </form>
    </div>
  </body>
</html>

Open in new window


processForm.php
<?php
 
// Clean up the input values
foreach($_POST as $key => $value) {
  if(ini_get('magic_quotes_gpc'))
    $_POST[$key] = stripslashes($_POST[$key]);
 
  $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
 
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
 
// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
  if(!$name) {
    $errors[] = "You must enter a Name Form.";
  } else {
    $errors[] = "Name must be at least 2 characters.";
  }
}

if(!$email) {
  $errors[] = "You must enter an email.";
} else if(!validEmail($email)) {
  $errors[] = "You must enter a valid email.";
}
if(strlen($message) < 3) {
  if(!$message) {
    $errors[] = "You must enter a message.";
  } else {
    $errors[] = "Message must be at least 10 characters.";
  }
}

 
if($errors) {
  // Output errors and die with a failure message
  $errortext = "";
  foreach($errors as $error) {
    $errortext .= "<li>".$error."</li>";
  }
  die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
}
 
// Send the email *********** enter your email address and message info *******************
$to = "youremail@youremail.com"; 
$subject = "Contact Form: $name";
$message = "$message";
$headers = "From: $email";
 
mail($to, $subject, $message, $headers);
 
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");

 
// A function that checks to see if
// an email is valid
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}
 
?>

Open in new window

0
Comment
Question by:mewebs
  • 3
  • 2
5 Comments
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39281979
At the moment your PHP script is just passing back a string using the die() function. You need to change that so you pass back an array of data containing a success/failure indicator and the response.

The easiest way to do this is to tell your AJAX script that you expect back a JSON string and then get your PHP script to generate one. Change your AJAX script to this:

$.post(url, data, null, 'json')
	.done( function(response) {
		if (response.success) {
			//'success' is true, so show the 'content' and hide the form
			$('#response').html(response.content);
			$('#contactform').hide();
		} else {
			//'success' is not true so just show the 'content'
			$('#response').html(response.content);
		}
	})
	.fail( function() {
		alert("The AJAX request failed!");
	});

Open in new window

Your PHP script now needs to pass back 2 variables - 'success' and 'content' - as a JSON string. Change line 46 to this:

$response = array(
    "success" => false,
    "content" => "<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>"
);
die(json_encode($response));

Open in new window

and line 58 to this:

$response = array(
    "success" => true,
    "content" => "<span class='success'>Success! Your message has been sent.</span>"
);
die(json_encode($response));

Open in new window

0
 

Author Comment

by:mewebs
ID: 39282053
Once again, perfect solution.  

I know this is outside of this question, but if you were going to do a simple contact form like this, is this what you would do - like I have?

If you have something better and simpler, I can ask another question on here to award points for a simple contact form, I would not expect you to not get points for it.

Just thought I would ask

Thanks for all your help!
0
 

Author Closing Comment

by:mewebs
ID: 39282072
works perfectly! thanks again
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39282344
For a simple contact form, I think you've pretty much got all the elements covered..
0
 

Author Comment

by:mewebs
ID: 39282377
Thanks. just checking to make sure. have a good day!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question