Solved

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

Posted on 2013-06-27
5
2,073 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

688 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