Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2470
  • Last Modified:

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

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
mewebs
Asked:
mewebs
  • 3
  • 2
1 Solution
 
Chris StanyonCommented:
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
 
mewebsAuthor Commented:
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
 
mewebsAuthor Commented:
works perfectly! thanks again
0
 
Chris StanyonCommented:
For a simple contact form, I think you've pretty much got all the elements covered..
0
 
mewebsAuthor Commented:
Thanks. just checking to make sure. have a good day!
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.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now