?
Solved

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

Posted on 2013-06-27
5
Medium Priority
?
2,121 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 2000 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

WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

Question has a verified solution.

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

Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
Suggested Courses

800 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