SitePoint Sponsor

User Tag List

Page 1 of 3 123 LastLast
Results 1 to 25 of 56
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Spam Honey Pot trap

    A complete newcomer to Javascript and PHP... I have now spent more time on the contact form than the rest of entire site put together!!!!

    I have a working (so far as I know) contact form. However it has zero in the way of security and came across a honeypot trap at:http://devgrow.com/simple-php-honey-pot/

    I have my own contact form with Javascript validation and would like to add the Honey Pot part only. I have my own Javascript error messages so what parts of the example PHP would I need to integrate and whats parts would I leave out?

    Below is the Honey Pot example and below that is my contact form.

    I think after I finish this contact form I'm going to start to study the various books on Javascript & PHP I bought recently!

    Honey Pot Example:
    Code:
    <html>
    <head>
    <title>Honey pot test</title>
    <!-- This example and tutorial can be found at http://devgrow.com/simple-php-honey-pot -->
    <style>
    	/* Optional Styling: */
    	body { background: #fafafa; font-size: 13px; font-family: Verdana; padding: 40px; }
    	fieldset { width: 280px; background: #fff; padding: 10px; display: block; }
    	legend { font-size: 18px; margin: 0; }
    	input, textarea { margin: 0; padding: 3px; border: 1px solid #aaa; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; width: 278px }
    	label { width: 100%; font-weight: bold; float: left; }
    	.submit { background: #444; color: #fff; width: inherit; border: none; padding: 5 10px; cursor: pointer; } .submit:hover { background: #000; }
    	.msg { padding: 10px; border: 1px solid #ccc; background: #fff; width: 285px; margin: 0 0 20px; }
    	.msg.success { border-color: #86a62f; background: #faffec; }
    	.msg.error { border-color: #cd5a5a; background: #fff7f7; }
    	
    	/* Required for Honey Pot: */
    	.robotic { display: none; }
    </style>
    <script type="text/javascript">
    	function showpot() {
    		document.getElementById("pot").className = "";
    		return false;
    	}
    </script>
    </head>
    <body>
    <?php
    	if($_POST){
    		$to = 'your-email-here@gmail.com';
    		$subject = 'Contact Form Submission';
    		$from_name = $_POST['name'];
    		$from_email = $_POST['email'];
    		$message = $_POST['message'];
    		$robotest = $_POST['robotest'];
    		if($robotest)
    			$error = "You are a gutless robot.";
    		else{
    			if($from_name && $from_email && $message){
    				$header = "From: $from_name <$from_email>";
    				if(mail($to, $subject, $message, $header))
    					$success = "You are human and your message was sent!";
    				else
    					$error = "You are human but there was a problem sending the e-mail.";
    			}else
    				$error = "All fields are required.";
    		}
    		if($error)
    			echo '<div class="msg error">'.$error.'</div>';
    		elseif($success)
    			echo '<div class="msg success">'.$success.'</div>';
    	}
    ?>
    <form method="post" action="">
    	<fieldset>
    		<legend>Contact Me</legend>
    		<p>
    			<label>Name:</label>
    			<input name="name" type="text" id="name" />
    		</p>
    		<p>
    			<label>E-mail:</label>
    			<input name="email" type="text" id="email" />
    		</p>
    		<p>
    			<label>Message:</label>
    			<textarea name="message" id="message"></textarea>
    		</p>
    		<!-- The following field is for robots only, invisible to humans: -->
    		<p class="robotic" id="pot">
    			<label>If you're human leave this blank:</label>
    			<input name="robotest" type="text" id="robotest" class="robotest" />
    		</p>
    		<p>
    			<input type="submit" value="Send Message" class="submit" />
    		</p>
    	</fieldset>
    </form>
    <br />
    <a href="#" onClick="showpot();">Show honey pot field?</a><br />
    <a href="http://devgrow.com/simple-php-honey-pot/">View Tutorial</a>
    </body>
    </html>
    My Contact Form - Work in Progress :
    Code:
    <!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>Pete's Contact Form with jQuery Validation</title>
    <script type="text/javascript" src="js/messages.js"></script>
     
    <style type="text/css">
    
    * {font-family: Arial, Helvetica, sans-serif;}
    	
    body { background-color: #999;}
    .form label { font-size: 90%;} 
    .required_notification { font-size: 80%;} 
    	   
    
     /*CONTACT FORM - LEFT DIV*/
    #input_wrapper { width: 500px;
    				padding: 10px 20px 20px 20px; 
    				background: #555;
                 	background: -moz-linear-gradient(top, #444 0%, #666 50%); /* firefox */
    	            background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #444), color-stop(50%, #666)); /* webkit */
    	            border-radius: 3px;
    	           -moz-border-radius: 3px;
    	           -webkit-border-radius: 3px;
    	           -webkit-box-shadow: 0px 2px 2px #333333;
    	            box-shadow: 0px 2px 2px #333333;}
    
    /*Padding/margins/borders/outlines settings*/
    input, textarea {
    	margin: 0;
    	padding: 0;
    	border: 0;
    	outline: none;}
    	
    /*Border Bottom*/		
    .form li:first-child, .contact_form li:last-child {
    	border-bottom:1px solid #CCC;}
    /*Border Bottom*/	
    
    /*Padding/margins/borders/outlines*/
    
    
    /*No glowing edges to inputs!!!*/
    *:focus {outline: none;}
    /*No glowing edges to inputs!!!*/
    	
    /*Header*/	
    .form h3 {
    	margin:0px;
    	display: inline;}
    	
    .required_notification {
    	color: #F06; /*#27AECF*/
    	margin:5px 0 0 0; 
    	display:inline;
    	float:right;}
    /*Header*/	
    
    
    /*Contact form labels*/
    .form ul {
        width:500px;
        list-style-type:none;
    	list-style-position:outside;
    	margin:0px;
    	padding:0px;}
    
    .form li{
    	color:#FFF;
    	padding:10px; 
    	border-bottom:1px solid #999;
    	position:relative;}
    	
    	
    .form label {
    	width:80px;
    	margin-top: 2px;
    	display:inline-block;
    	float:left;
    	padding:3px;}
    	
    #msg {display:none; 
          font-size:75%;
          position:absolute; 
    	  z-index:200; 
    	  background: url(images/msg_arrow.gif) left center no-repeat; 
    	  padding-left:7px;}
    	  
    #msgcontent {display:block; 
                  background: #D6D6D6; 
    			  border:2px solid #F06; 
    			  border-left:none; 
    			  padding:5px; 
    			  min-width:192px; 
    			  max-width:192px;}
    	  
    			  
    /*Contact form labels*/
    
    
    /*Contact form inputs*/
    .form input:focus, .form textarea:focus { background-color: #EBEBEB;}
    
    /*Contact form text fields*/
    .form input { 
        font-family:Arial, Helvetica, sans-serif;
    	font-size: 80%;
     	background-color: #D6D6D6;
    	/*border:1px solid #aaa;*/ 
    	height:20px; 
    	width:180px; 
    	margin: 0px;
    	padding:2px 5px;
    	border-radius: 2px;
    	-moz-border-radius: 2px;
    	-webkit-border-radius: 2px;}
    /*Contact form text fields*/
    
    
    /*Contact textarea*/
    .form textarea { font-family:Arial, Helvetica, sans-serif; 
                             font-size: 80%;
                             width: 240px;
                             height: 100px;
                             padding: 5px 5px;
                             background-color: #D6D6D6;/*padding-right:30px;*/
    		                 /*border:1px solid #aaa;*/
    		                 border-radius: 2px;
                         	 -moz-border-radius: 2px;
    	                     -webkit-border-radius: 2px;}
    /*Contact textarea*/	
    					 
    /*Contact form inputs*/
    
    
    /*input/textarea placeholder text*/
    input::-webkit-input-placeholder { color: #777;}
    
    input:-moz-placeholder { color: #777;}
    
    ::-webkit-input-placeholder { color: #777;}
    	
    :-moz-placeholder { color: #777;}
    /*input/textarea placeholder text*/
    
    	
    /*sprite email button*/	
    
    input.submit { width: 148px; 
                   height: 40px;
    	           margin-left: 190px;
    	           background-position: 0px 0px;
    	           background-color: transparent; /* or #666*/
    	           background-image: url(images/email_sprite.png);
    	           /*background:transparent url(images/email_sprite.png);*/
    	           text-indent: -9999px;
    	           display: inline-block; 
    	           border:none;
    			   outline:none;} 
    			   
    input.submit:hover { background-position: 0px -40px;}
    
    input.submit:active { background-position: 0px -80px;}
    
    /*sprite email button*/		
    
    /*CONTACT FORM - LEFT DIV*/	
    </style>
    
    </head>
    
    <body>
    <div id="input_wrapper">
          <form name="form" id="form" class="form" action="" onsubmit="return validate(this)" method="post">
          
            <ul>
            
            <li>
                 <h3>Contact Us</h3>
                 <span class="required_notification">* Denotes Required Field</span>
            </li>
            
            <li>
              <label for="name">Name:</label>
              <input type="text" name="name" id="name" placeholder="Enter your full name *" />
            </li>
              
            <li>
              <label for="email">Email:</label>
              <input type="text" name="email" id="email" placeholder="Enter your email address *" />
            </li>
          
            <li>
              <label for="telephone">Phone:</label>
              <input type="text" name="landline" id="landline" placeholder="Enter your landline number *" />
            </li>  
              
            <li>  
              <label for="mobile">Mobile:</label>
              <input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number *" />
           </li> 
           
            <li>  
              <label for="message">Message:</label>
              <textarea id="message" name="message" placeholder="Enter your message here...*"></textarea>     
           </li>
           
           <li>
            <input type="submit" value="submit" class="submit"/>
            </li>
           </ul>
          </form>
        </div>
    </body>
    </html>

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    To implement this technique you need to do the following:

    Add this to your HTML:

    HTML Code:
    <!-- The following field is for robots only, invisible to humans: -->
    <li class="robotic" id="pot">
      <label for="robotest">If you're human leave this blank:</label>
      <input name="robotest" id="robotest" class="robotest" type="text" />
    </li>
    Add this to your CSS:

    Code CSS:
    .robotic { display:none; }

    What you add to your PHP will depend on how what you already have.
    Basically, we can break it down into the following:

    PHP Code:
    $robotest $_POST['robotest']; 
    This fetches whichever value was submitted in the robotest field and stores it in a variable named $robotest

    PHP Code:
    if($robotest){
      
    we are dealing with a bot
    else{
      
    we are dealing with a human
     

    This will check to see if there is anything stored in the variable $robotest.
    In his example the author just adds an error to the $error variable to display.
    You could also have the form just fall over and die.

    Hope that helps.

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So something like this? If I take anything else out it I get syntax errors. My contact form has validation except for a success message. So I could keep the PHP as below?

    Having no experience in Javascript & PHP I find it all frustrating! So don't be afraid to explain t in a way a complete dummy could understand! ...And Happy New Year!

    Code:
    <?php
    	if($_POST){
    		$robotest = $_POST['robotest'];
    		if($robotest)
    			$error = "die robot.";
    		else{
    			$success = "You are human and your message was sent!";
    				
    		}
    		if($success)
    			echo '<div class="msg success">'.$success.'</div>';
    	}
    ?>
    Alternatively to keep things tidy could the above PHP be integrated in to my current validation form below?

    Code:
    // form validation function //
    function validate(form) {
      var name = form.name.value;
      var email = form.email.value;
      var message = form.message.value;
      var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
      var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
      var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
      if(name == "") {
        inlineMsg('name','Please enter your name!',2);
        return false;
      }
      if(!name.match(nameRegex)) {
        inlineMsg('name','Please enter an invalid name!',2);
        return false;
      }
      if(email == "") {
        inlineMsg('email','<strong>Error!</strong> Please enter your email!',2);
        return false;
      }
      if(!email.match(emailRegex)) {
        inlineMsg('email','<strong>Error!</strong> This email is invalid!',2);
        return false;
      }
      if(message == "") {
        inlineMsg('message','Please enter your message!');
        return false;
      }
      if(message.match(messageRegex)) {
        inlineMsg('message','This message is invalid!');
        return false;
      }
      return true;
    }
    
    // START OF MESSAGE SCRIPT //
    
    var MSGTIMER = 20;
    var MSGSPEED = 5;
    var MSGOFFSET = 3;
    var MSGHIDE = 3;
    
    // build out the divs, set attributes and call the fade function //
    function inlineMsg(target,string,autohide) {
      var msg;
      var msgcontent;
      if(!document.getElementById('msg')) {
        msg = document.createElement('div');
        msg.id = 'msg';
        msgcontent = document.createElement('div');
        msgcontent.id = 'msgcontent';
        document.body.appendChild(msg);
        msg.appendChild(msgcontent);
        msg.style.filter = 'alpha(opacity=0)';
        msg.style.opacity = 0;
        msg.alpha = 0;
      } else {
        msg = document.getElementById('msg');
        msgcontent = document.getElementById('msgcontent');
      }
      msgcontent.innerHTML = string;
      msg.style.display = 'block';
      var msgheight = msg.offsetHeight;
      var targetdiv = document.getElementById(target);
      targetdiv.focus();
      var targetheight = targetdiv.offsetHeight;
      var targetwidth = targetdiv.offsetWidth;
      var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
      var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
      msg.style.top = topposition + 'px';
      msg.style.left = leftposition + 'px';
      clearInterval(msg.timer);
      msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
      if(!autohide) {
        autohide = MSGHIDE;  
      }
      window.setTimeout("hideMsg()", (autohide * 1000));
    }
    
    // hide the form alert //
    function hideMsg(msg) {
      var msg = document.getElementById('msg');
      if(!msg.timer) {
        msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
      }
    }
    
    // face the message box //
    function fadeMsg(flag) {
      if(flag == null) {
        flag = 1;
      }
      var msg = document.getElementById('msg');
      var value;
      if(flag == 1) {
        value = msg.alpha + MSGSPEED;
      } else {
        value = msg.alpha - MSGSPEED;
      }
      msg.alpha = value;
      msg.style.opacity = (value / 100);
      msg.style.filter = 'alpha(opacity=' + value + ')';
      if(value >= 99) {
        clearInterval(msg.timer);
        msg.timer = null;
      } else if(value <= 1) {
        msg.style.display = "none";
        clearInterval(msg.timer);
      }
    }
    
    // calculate the position of the element in relation to the left of the browser //
    function leftPosition(target) {
      var left = 0;
      if(target.offsetParent) {
        while(1) {
          left += target.offsetLeft;
          if(!target.offsetParent) {
            break;
          }
          target = target.offsetParent;
        }
      } else if(target.x) {
        left += target.x;
      }
      return left;
    }
    
    // calculate the position of the element in relation to the top of the browser window //
    function topPosition(target) {
      var top = 0;
      if(target.offsetParent) {
        while(1) {
          top += target.offsetTop;
          if(!target.offsetParent) {
            break;
          }
          target = target.offsetParent;
        }
      } else if(target.y) {
        top += target.y;
      }
      return top;
    }
    
    // preload the arrow //
    if(document.images) {
      arrow = new Image(7,80); 
      arrow.src = "images/msg_arrow.gif"; 
    }

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    The PHP code looks fine.
    I wouldn't try and integrate it into the JavaScript, rather into your existing PHP code.

    Could you post the contents of the PHP script to which your form is submitted.

  5. #5
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    72 Post(s)
    Tagged
    0 Thread(s)
    $_POST always exists; it's a superglobal. Try checking for a specific value of $_POST, not for the array itself.
    Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.

  6. #6
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    Hi there,

    The PHP code looks fine.
    I wouldn't try and integrate it into the JavaScript, rather into your existing PHP code.

    Could you post the contents of the PHP script to which your form is submitted.
    Showing up my ignorance again here!

    Currently it only has the Javascript validation and no PHP. What other PHP do I need?

    On a positive note I've set up MAMP!

  7. #7
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    JavaScript validation is fine for most cases, but it is implemented client-side, i.e. in your users' browser.
    This means that if I turn JavaScript off at my end, I can completely bypass your validation and the form will always submit regardless of what I enter.

    PHP validation on the other hand takes place on a remote server and cannot be bypassed by anyone.
    It is also a good idea to use PHP (or any other server-side language) to sanitize any user input before processing it, especially if you are saving user input to a data base.

    Before we get into the best way for you to implement this, I'm curious: how are you actually sending your mail, as this is not something you can do using JavaScript alone.

    Let me know and I'm sure we can get to the bottom of this.

  8. #8
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ... yes I see what you mean. So in my contact forms HTML i need to link in a PHP document like this:

    Code:
    form name="form" id="form" class="form" action="form_to_email.php" onsubmit="return validate(this)" method="post">
    Basically I haven't got the necessary PHP skills to create such a document!

  9. #9
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    No problem. I can help you make the PHP script to power the form.
    Client side validation is still valuable, as it makes the form feel snappier and is nicer for your users. You don't have to bin your work so far!

    I'll put something together, using your form above as a template and incorporating the spam trap. Then I'll get back to you tomorrow (it's late here and I'm turning in soon).

    Edit: One question. You do have access to a PHP environment with a mail server, don't you? Most web hosting companies provide this. The sending mail part won't work locally (i.e. MAMP) without further configuration.

  10. #10
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Meh, who needs sleep?

    Here's your contact form:

    Code:
    <!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>Pete's Contact Form with jQuery Validation</title>
        <script type="text/javascript" src="js/messages.js"></script>
        <style type="text/css">
          * {font-family: Arial, Helvetica, sans-serif;}
          body { background-color: #999;}
          .form label { font-size: 90%;} 
          .required_notification { font-size: 80%;} 
          
          /*CONTACT FORM - LEFT DIV*/
          #input_wrapper { width: 500px;
          padding: 10px 20px 20px 20px; 
          background: #555;
          background: -moz-linear-gradient(top, #444 0%, #666 50%); /* firefox */
          background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #444), color-stop(50%, #666)); /* webkit */
          border-radius: 3px;
          -moz-border-radius: 3px;
          -webkit-border-radius: 3px;
          -webkit-box-shadow: 0px 2px 2px #333333;
          box-shadow: 0px 2px 2px #333333;}
          
          /*Padding/margins/borders/outlines settings*/
          input, textarea {
          margin: 0;
          padding: 0;
          border: 0;
          outline: none;}
          
          /*Border Bottom*/    
          .form li:first-child, .contact_form li:last-child {
          border-bottom:1px solid #CCC;}
          /*Border Bottom*/  
          
          /*Padding/margins/borders/outlines*/
          
          /*No glowing edges to inputs!!!*/
          *:focus {outline: none;}
          /*No glowing edges to inputs!!!*/
          
          /*Header*/  
          .form h3 {
          margin:0px;
          display: inline;}
          
          .required_notification {
          color: #F06; /*#27AECF*/
          margin:5px 0 0 0; 
          display:inline;
          float:right;}
          /*Header*/  
          
          /*Contact form labels*/
          .form ul {
          width:500px;
          list-style-type:none;
          list-style-position:outside;
          margin:0px;
          padding:0px;}
          
          .form li{
          color:#FFF;
          padding:10px; 
          border-bottom:1px solid #999;
          position:relative;}
          
          .form label {
          width:80px;
          margin-top: 2px;
          display:inline-block;
          float:left;
          padding:3px;}
          
          #msg {display:none; 
          font-size:75%;
          position:absolute; 
          z-index:200; 
          background: url(images/msg_arrow.gif) left center no-repeat; 
          padding-left:7px;}
          
          #msgcontent {display:block; 
          background: #D6D6D6; 
          border:2px solid #F06; 
          border-left:none; 
          padding:5px; 
          min-width:192px; 
          max-width:192px;}
          
          /*Contact form labels*/
          
          /*Contact form inputs*/
          .form input:focus, .form textarea:focus { background-color: #EBEBEB;}
          
          /*Contact form text fields*/
          .form input { 
          font-family:Arial, Helvetica, sans-serif;
          font-size: 80%;
          background-color: #D6D6D6;
          /*border:1px solid #aaa;*/ 
          height:20px; 
          width:180px; 
          margin: 0px;
          padding:2px 5px;
          border-radius: 2px;
          -moz-border-radius: 2px;
          -webkit-border-radius: 2px;}
          /*Contact form text fields*/
          
          /*Contact textarea*/
          .form textarea { font-family:Arial, Helvetica, sans-serif; 
          font-size: 80%;
          width: 240px;
          height: 100px;
          padding: 5px 5px;
          background-color: #D6D6D6;/*padding-right:30px;*/
          /*border:1px solid #aaa;*/
          border-radius: 2px;
          -moz-border-radius: 2px;
          -webkit-border-radius: 2px;}
          /*Contact textarea*/  
          
          /*Contact form inputs*/
          
          /*input/textarea placeholder text*/
          input::-webkit-input-placeholder { color: #777;}
          input:-moz-placeholder { color: #777;}
          ::-webkit-input-placeholder { color: #777;}
          :-moz-placeholder { color: #777;}
          /*input/textarea placeholder text*/
          
          /*sprite email button*/  
          input.submit { width: 148px; 
          height: 40px;
          margin-left: 190px;
          background-position: 0px 0px;
          background-color: transparent; /* or #666*/
          background-image: url(images/email_sprite.png);
          /*background:transparent url(images/email_sprite.png);*/
          text-indent: -9999px;
          display: inline-block; 
          border:none;
          outline:none;} 
          
          input.submit:hover { background-position: 0px -40px;}
          input.submit:active { background-position: 0px -80px;}
          /*sprite email button*/    
          
          .robotic { display:none; }
          
          /*CONTACT FORM - LEFT DIV*/  
        </style>
      </head>
      
      <body>
        <div id="input_wrapper">
          <form name="form" id="form" class="form" action="myScript.php" onsubmit="return validate(this)" method="post">
            <ul>
              <li>
                <h3>Contact Us</h3>
                <span class="required_notification">* Denotes Required Field</span>
              </li>
              <li>
                <label for="name">Name:</label>
                <input type="text" name="name" id="name" placeholder="Enter your full name *" />
              </li>
              <li>
                <label for="email">Email:</label>
                <input type="text" name="email" id="email" placeholder="Enter your email address *" />
              </li>
              <li>
                <label for="telephone">Phone:</label>
                <input type="text" name="landline" id="landline" placeholder="Enter your landline number *" />
              </li>  
              <li>  
                <label for="mobile">Mobile:</label>
                <input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number *" />
              </li> 
              <li>  
                <label for="message">Message:</label>
                <textarea id="message" name="message" placeholder="Enter your message here...*"></textarea>     
              </li>
              
              <!-- The following field is for robots only, invisible to humans: -->
              <li class="robotic">
                <label for="robotest">If you're human leave this blank:</label>
                <input type="text" id="robotest" name="robotest" class="robotest" />
              </li>  
                      
              <li>
                <input type="submit" value="submit" class="submit"/>
              </li>
            </ul>
          </form>
        </div>
        
        <script>
          // form validation function //
          function validate(form) {
            var name = form.name.value;
            var email = form.email.value;
            var message = form.message.value;
            var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
            var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
            var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
            if(name == "") {
              inlineMsg('name','Please enter your name!',2);
              return false;
            }
            if(!name.match(nameRegex)) {
              inlineMsg('name','Please enter an invalid name!',2);
              return false;
            }
            if(email == "") {
              inlineMsg('email','<strong>Error!</strong> Please enter your email!',2);
              return false;
            }
            if(!email.match(emailRegex)) {
              inlineMsg('email','<strong>Error!</strong> This email is invalid!',2);
              return false;
            }
            if(message == "") {
              inlineMsg('message','Please enter your message!');
              return false;
            }
            if(message.match(messageRegex)) {
              inlineMsg('message','This message is invalid!');
              return false;
            }
            return true;
          }
          
          // START OF MESSAGE SCRIPT //
          
          var MSGTIMER = 20;
          var MSGSPEED = 5;
          var MSGOFFSET = 3;
          var MSGHIDE = 3;
          
          // build out the divs, set attributes and call the fade function //
          function inlineMsg(target,string,autohide) {
            var msg;
            var msgcontent;
            if(!document.getElementById('msg')) {
              msg = document.createElement('div');
              msg.id = 'msg';
              msgcontent = document.createElement('div');
              msgcontent.id = 'msgcontent';
              document.body.appendChild(msg);
              msg.appendChild(msgcontent);
              msg.style.filter = 'alpha(opacity=0)';
              msg.style.opacity = 0;
              msg.alpha = 0;
            } else {
              msg = document.getElementById('msg');
              msgcontent = document.getElementById('msgcontent');
            }
            msgcontent.innerHTML = string;
            msg.style.display = 'block';
            var msgheight = msg.offsetHeight;
            var targetdiv = document.getElementById(target);
            targetdiv.focus();
            var targetheight = targetdiv.offsetHeight;
            var targetwidth = targetdiv.offsetWidth;
            var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
            var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
            msg.style.top = topposition + 'px';
            msg.style.left = leftposition + 'px';
            clearInterval(msg.timer);
            msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
            if(!autohide) {
              autohide = MSGHIDE;  
            }
            window.setTimeout("hideMsg()", (autohide * 1000));
          }
          
          // hide the form alert //
          function hideMsg(msg) {
            var msg = document.getElementById('msg');
            if(!msg.timer) {
              msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
            }
          }
          
          // face the message box //
          function fadeMsg(flag) {
            if(flag == null) {
              flag = 1;
            }
            var msg = document.getElementById('msg');
            var value;
            if(flag == 1) {
              value = msg.alpha + MSGSPEED;
            } else {
              value = msg.alpha - MSGSPEED;
            }
            msg.alpha = value;
            msg.style.opacity = (value / 100);
            msg.style.filter = 'alpha(opacity=' + value + ')';
            if(value >= 99) {
              clearInterval(msg.timer);
              msg.timer = null;
            } else if(value <= 1) {
              msg.style.display = "none";
              clearInterval(msg.timer);
            }
          }
          
          // calculate the position of the element in relation to the left of the browser //
          function leftPosition(target) {
            var left = 0;
            if(target.offsetParent) {
              while(1) {
                left += target.offsetLeft;
                if(!target.offsetParent) {
                  break;
                }
                target = target.offsetParent;
              }
            } else if(target.x) {
              left += target.x;
            }
            return left;
          }
          
          // calculate the position of the element in relation to the top of the browser window //
          function topPosition(target) {
            var top = 0;
            if(target.offsetParent) {
              while(1) {
                top += target.offsetTop;
                if(!target.offsetParent) {
                  break;
                }
                target = target.offsetParent;
              }
            } else if(target.y) {
              top += target.y;
            }
            return top;
          }
          
          // preload the arrow //
          if(document.images) {
            arrow = new Image(7,80); 
            arrow.src = "images/msg_arrow.gif"; 
          }
        </script>
      </body>
    </html>
    And here's the script it should submit to (currently named myScript.php):

    PHP Code:
    <?php
      $name   
    strip_tags($_POST['name']);
      
    $email  strip_tags($_POST['email']);
      
    $landline  $_POST['landline'];
      
    $mobile  $_POST['mobile'];
      
    $message strip_tags($_POST['message']);
      
    $robotest $_POST['robotest']; 
          
      if(
    $robotest){
        echo 
    "We think you're a bot!";
        exit;
      }else{
        if (empty(
    $name)){
          
    $error .= "You didn't enter a name <br />";
        }
        
        if (empty(
    $email)){
          
    $error .= "You didn't enter an email address <br />";
        } elseif (!
    eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})\.?$"$email)){
          
    $error .= "The email address appears to be invalid <br />";  
        }
        
        if (empty(
    $landline)){
          
    $error .= "You didn't enter a landline number <br />";
        } elseif (!
    eregi("^[0-9()+\s-]+$"$landline)){
          
    $error .= "The landline number can only contain digits, spaces, brackets, plus or minus <br />";  
        }
        
        if (empty(
    $mobile)){
          
    $error .= "You didn't enter a mobile number <br />";
        } elseif (!
    eregi("^[0-9()+\s-]+$"$mobile)){
          
    $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
        }
        
        if (empty(
    $message)){
          
    $error .= "You didn't enter a message <br />";
        }
      }  
     
      if (empty(
    $error)) {
        
    $newLine chr(13).chr(10);
        
    $adress "your email address here";
        
    $subject "Message from contact form";
        
    $from "From: Contact Form <noreply@yourdomain.com>";
        
    $date "Date: ".date("j.n.Y").$newLine;
        
    $time "Time: ".date("H:i").$newLine;
        
    $sender "From: ".$name." <".$email.">".$newLine;
        
    $divider ="-------------------".$newLine.$newLine;
        
    $text $date.$time.$sender.$divider.$message;
        
    mail($adress$subject$text$from);
        
    header("location: http://www.sitepoint.com");
      } else {
        echo 
    $error;
        echo 
    "<p><strong>Please use your browser's back button and rectify this!</strong></p>";
        exit;
      }
    ?>
    Be sure to enter your correct email address and other details at the end of the script.
    You can also change the url specified in header() so that the form redirects to a page of your choosing upon successful submission.

    If you have any questions, just let me know.

  11. #11
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Indeed who needs sleep! Thanks for all your help we are almost there!

    I gave it a test on MAMP and I managed to send myself a test message. No access to a PHP environment as yet as the website owner can't get his act together and send me the login details! Which reminds me I need to download Transmit.


    A few final things which i'd like to resolve so I can finish the site, move on, and start actually spending my time learning Javascript & PHP. Once its done I'll post it up for evaluation.

    • On submitting the form I'm directed to a blank page with http://localhost:8888/myScript.php in the URL. On submit I would like to stay on the same page and receive a success message next to the submit button (see the attached image)
    • The email I get from the test message displays the message only, no name or phone numbers
    • The mobile phone needs to be changed to non-required field.... I'll probably delete something vital!


    Currently experimenting with the PHP below to get a success! message on submit. I can just about style the positioning with CSS. Mixed success so far though because its late and I'm sleepy!

    PHP Code:
    <?php
        
    if($_POST){
            
    $robotest $_POST['robotest'];
            if(
    $robotest)
                
    $error "die robot.";
            else{
                
    $success "You are human and your message was sent!";
                    
            }
            if(
    $success)
                echo 
    '<div class="msg success">'.$success.'</div>';
        }
    ?>
    sucesss-message.jpg

  12. #12
    SitePoint Wizard TheRedDevil's Avatar
    Join Date
    Sep 2004
    Location
    Norway
    Posts
    1,196
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    Be sure to enter your correct email address and other details at the end of the script.
    You can also change the url specified in header() so that the form redirects to a page of your choosing upon successful submission.

    If you have any questions, just let me know.
    I am sorry, but no one should ever use that code without updating the validation section.

    You can insert additional headers without a problem, meaning I can use the contact form as my own spam tool.

    Take a look on this for more information:
    http://www.securephpwiki.com/index.php/Email_Injection

  13. #13
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    @TheRedDevil ;

    Quote Originally Posted by TheRedDevil View Post
    I am sorry, but no one should ever use that code without updating the validation section.

    You can insert additional headers without a problem, meaning I can use the contact form as my own spam tool.
    Thank you for pointing this out in a constructive manner.
    Of course, you are correct.

    I've reworked the PHP script to include proper validation and have tidied everything else up a bit:

    PHP Code:
    <?php
      $name 
    filter_var($_POST['name'],FILTER_SANITIZE_STRING);
      
    $email filter_var($_POST['email'],FILTER_SANITIZE_STRINGFILTER_VALIDATE_EMAIL);
      
    $landline filter_var($_POST['landline'], FILTER_SANITIZE_STRING);
      
    $mobile filter_var($_POST['mobile'], FILTER_SANITIZE_STRING);
      
    $message filter_var($_POST['message'],FILTER_SANITIZE_STRING);
      
    $robotest $_POST['robotest']; 
          
      if(
    $robotest){
        exit(
    "Sorry, we think you're a bot!");
      }
      
      if (empty(
    $name)){
        
    $error .= "You didn't enter a name <br />";
      }
      
      if (empty(
    $email)){
        
    $error .= "You didn't enter an email address <br />";
      } elseif (!
    eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})\.?$"$email)){
        
    $error .= "The email address appears to be invalid <br />";  
      }
      
      if (empty(
    $landline)){
        
    $error .= "You didn't enter a landline number <br />";
      } elseif (!
    eregi("^[0-9()+\s-]+$"$landline)){
        
    $error .= "The landline number can only contain digits, spaces, brackets, plus or minus <br />";  
      }
      
      if (empty(
    $mobile)){
        
    $error .= "You didn't enter a mobile number <br />";
      } elseif (!
    eregi("^[0-9()+\s-]+$"$mobile)){
        
    $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
      }
      
      if (empty(
    $message)){
        
    $error .= "You didn't enter a message <br />";
      }
      
      if (empty(
    $error)) {
        
    $toaddress "your email address here";
        
    $fromaddress "From:"$email;
        
        
    $mailcontent "Name: "$name"\n".
                       
    "Email: "$email"\n\n".
                       
    $message;
                       
        
    mail($toaddress"Website Contact Form"$mailcontent$fromaddress);
        
    header("location: http://www.sitepoint.com");
      } else {
        echo 
    $error;
        echo 
    "<p><strong>Please use your browser's back button and rectify this!</strong></p>";
        exit();
      }
    ?>
    If you can see anything I've missed, then please let me know.

  14. #14
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by designclash View Post
    Indeed who needs sleep!
    Me, this morning!

    Quote Originally Posted by designclash View Post
    I gave it a test on MAMP and I managed to send myself a test message.
    Ok, I didn't realize that worked.
    I normally use xampp and you have to set up a mail server, which I have never bothered doing.

    Quote Originally Posted by designclash View Post
    On submitting the form I'm directed to a blank page with http://localhost:8888/myScript.php in the URL.
    Weird! You should be redirected to Sitepoint.
    Try updating the code I posted last night, with the code I posted above and then see what happens.

    Quote Originally Posted by designclash View Post
    On submit I would like to stay on the same page and receive a success message next to the submit button (see the attached image)
    I'm not too sure about this.
    Normally you redirect your users to a "success" page on successful submission.
    The reason for this is that if you bring them back to the same page, they can resubmit the form by reloading the page.
    This would mean that someone could keep sending you mails, by pressing F5 over and over.
    Saying that though, it must be possible.

    Quote Originally Posted by designclash View Post
    The email I get from the test message displays the message only, no name or phone numbers.
    Again. This is bizarre. It works fine for me.

    Quote Originally Posted by designclash View Post
    The mobile phone needs to be changed to non-required field.... I'll probably delete something vital!
    No probs. In the above code, change this:

    PHP Code:
    if (empty($mobile)){
      
    $error .= "You didn't enter a mobile number <br />";
    } elseif (!
    eregi("^[0-9()+\s-]+$"$mobile)){
      
    $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  

    to this:

    PHP Code:
    if (!empty($mobile) && !eregi("^[0-9()+\s-]+$"$mobile)){
      
    $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  

    Quote Originally Posted by designclash View Post
    Currently experimenting with the PHP below to get a success! message on submit.
    PHP Code:
    <?php
        
    if($_POST){
            
    $robotest $_POST['robotest'];
            if(
    $robotest)
                
    $error "die robot.";
            else{
                
    $success "You are human and your message was sent!";
                    
            }
            if(
    $success)
                echo 
    '<div class="msg success">'.$success.'</div>';
        }
    ?>
    As StarLion mentioned, $_POST always exists and you don't need to test for it.
    That means you could write:

    PHP Code:
    <?php
    $robotest 
    $_POST['robotest'];
    if(
    $robotest)
      exit(
    "die robot.");
    else{
      echo 
    '<div class="msg success">You are human and your message was sent!</div>';
    }
    ?>
    What I would suggest you do from here, is have a play around with the code and try to understand what is going on.
    Try updating the code I provided, then post back here if there is anything that still isn't working.

    Hope this helps.

  15. #15
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,
    Yes the code works well.

    I see what you mean about redirecting users after submitting a contact form. Just created a quick success page with a message and a link to return back.

    My idea is to achieve something along the lines on my attached image. Replacing the contact form DIV with a new one displaying a success message. Would this be acceptable?

    Test emails still kind of work. I get name, email and message. No numbers. Maybe a Mac thing or MAMP settings? Though I can't see why.

    Continuing to have a play around and get a grasp of whats going on. I have now about 15 versions of the same form.

    Well its all good practice. My rowing club needs a new website so after I've hit the books and got a bit more experience I'll give that site a redesign too. Web developing is quite addictive and before I know it I've spent hours inside a time vaccum and its 3.00am in the morning!


    successpage.jpg

  16. #16
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Good to hear things are progressing well.

    Let's tackle the test email situation first and make sure that all of the values get through.

    In the PHP code I provided this morning, can you change this:

    PHP Code:
    $mailcontent "Name: "$name"\n".
                   
    "Email: "$email"\n\n".
                   
    $message
    to this:

    PHP Code:
    $mailcontent "Name: "$name"\n".
                   
    "Email: "$email"\n".
                   
    "Landline: "$landline"\n".
                   
    "Mobile: "$mobile"\n\n".
                   
    $message
    Does that help any?

  17. #17
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes spot on! All the values get through. The only quirk is that how the test email displays. I typed "I am hungry. What's for dinner?" and got am hungry. What&#39;s for dinner?. It doesn't like apostrophes! Never mind though its only a minor detail.

    Finally the success page. I've attached an image of how the page should look. The contact form div is redirected to a new div which displays a success message and send another email option.

    To get a rough idea of how it will look I've just duplicated and renamed the page, replacing the contact form. So on submit you are redirected to a the new page. However I think just swapping the DIVs would be neater than linking in a whole new page

    successpage.jpg

    I definitely under estimated (as lots of people do) the complexity of developing a site. Most non techies seem to think its all drag and drop. I actually showed someone the markup and scripts and they were amazed at the complexity. Coming from a print/graphic background and fairly savvy on a mac I thought it'd be easy to pick up... my opinion has now changed!

  18. #18
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,656
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    I never new how to do honeypot really either. So I just worked one up. Might help http://www.visibilityinherit.com/cod...p-honeypot.php

  19. #19
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Evening,

    I've been doing some research and it seems that if the form does a HTTP redirect on itself, then the last "action" the browser remembers is a simple GET, so the form cannot be resubmitted upon refresh.

    I've worked this into a code example for you.
    As before you will have to alter your email address.
    Also you will have to alter this line accordingly:

    PHP Code:
    header("location: your-contact-form-address.php?success=1"); 
    It should read something like

    PHP Code:
    header("location: http://localhost/projects/contact.php?success=1"); 
    Other than that, have a play around with it and see if it works for you.
    The error messages etc, will need styling.

    BTW: I am using

    PHP Code:
    <?php echo htmlspecialchars($nameENT_QUOTES); ?>
    to repopulate the form with user input in the case of failed validation.
    Printing user input back to the screen is always a security risk, so once we get this working, it is probably a good idea to start a new thread to find out if this is sufficient protection (or, if anyone is listening and knows the answer, please feel free to chime in).

    PHP Code:
    <?php
        $name 
    '';
        
    $email =  '';
        
    $landline =  '';
        
    $mobile =  '';
        
    $message =  '';
         
      if (
    $_POST['s'] == 's'){
        
    $name filter_var($_POST['name'],FILTER_SANITIZE_STRING);
        
    $email filter_var($_POST['email'],FILTER_SANITIZE_STRINGFILTER_VALIDATE_EMAIL);
        
    $landline filter_var($_POST['landline'], FILTER_SANITIZE_STRING);
        
    $mobile filter_var($_POST['mobile'], FILTER_SANITIZE_STRING);
        
    $message filter_var($_POST['message'],FILTER_SANITIZE_STRING);
        
    $robotest $_POST['robotest']; 
          
        if(
    $robotest){
          exit(
    "Sorry, we think you're a bot!");
        }
        
        if (empty(
    $name)){
          
    $error .= "You didn't enter a name <br />";
        }
        
        if (empty(
    $email)){
          
    $error .= "You didn't enter an email address <br />";
        } elseif (!
    eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})\.?$"$email)){
          
    $error .= "The email address appears to be invalid <br />";  
        }
        
        if (empty(
    $landline)){
          
    $error .= "You didn't enter a landline number <br />";
        } elseif (!
    eregi("^[0-9()+\s-]+$"$landline)){
          
    $error .= "The landline number can only contain digits, spaces, brackets, plus or minus <br />";  
        }
        
        
    // Optional Field
        
    if (!empty($mobile) && !eregi("^[0-9()+\s-]+$"$mobile)){
          
    $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
        }  
        
        if (empty(
    $message)){
          
    $error .= "You didn't enter a message <br />";
        }
        
        if (empty(
    $error)) {
          
    $toaddress "your email address here";
          
    $fromaddress "From:"$email;
          
          
    $mailcontent "Name: "$name"\n".
                         
    "Email: "$email"\n".
                         
    "Landline: "$landline"\n".
                         
    "Mobile: "$mobile"\n\n".
                         
    $message;  
                                        
          
    mail($toaddress"Website Contact Form"$mailcontent$fromaddress);
          
    header("location: your-contact-form-address.php?success=1");
        } else {
          echo 
    $error;
        }
      }
      
      if (
    $_GET['success']){
        echo(
    "Message sent successfully");
      }
    ?>

    <!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>Pete's Contact Form with jQuery Validation</title>
        <script type="text/javascript" src="js/messages.js"></script>
        <style type="text/css">
          * {font-family: Arial, Helvetica, sans-serif;}
          body { background-color: #999;}
          .form label { font-size: 90%;} 
          .required_notification { font-size: 80%;} 
          
          /*CONTACT FORM - LEFT DIV*/
          #input_wrapper { width: 500px;
          padding: 10px 20px 20px 20px; 
          background: #555;
          background: -moz-linear-gradient(top, #444 0%, #666 50%); /* firefox */
          background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #444), color-stop(50%, #666)); /* webkit */
          border-radius: 3px;
          -moz-border-radius: 3px;
          -webkit-border-radius: 3px;
          -webkit-box-shadow: 0px 2px 2px #333333;
          box-shadow: 0px 2px 2px #333333;}
          
          /*Padding/margins/borders/outlines settings*/
          input, textarea {
          margin: 0;
          padding: 0;
          border: 0;
          outline: none;}
          
          /*Border Bottom*/    
          .form li:first-child, .contact_form li:last-child {
          border-bottom:1px solid #CCC;}
          /*Border Bottom*/  
          
          /*Padding/margins/borders/outlines*/
          
          /*No glowing edges to inputs!!!*/
          *:focus {outline: none;}
          /*No glowing edges to inputs!!!*/
          
          /*Header*/  
          .form h3 {
          margin:0px;
          display: inline;}
          
          .required_notification {
          color: #F06; /*#27AECF*/
          margin:5px 0 0 0; 
          display:inline;
          float:right;}
          /*Header*/  
          
          /*Contact form labels*/
          .form ul {
          width:500px;
          list-style-type:none;
          list-style-position:outside;
          margin:0px;
          padding:0px;}
          
          .form li{
          color:#FFF;
          padding:10px; 
          border-bottom:1px solid #999;
          position:relative;}
          
          .form label {
          width:80px;
          margin-top: 2px;
          display:inline-block;
          float:left;
          padding:3px;}
          
          #msg {display:none; 
          font-size:75%;
          position:absolute; 
          z-index:200; 
          background: url(images/msg_arrow.gif) left center no-repeat; 
          padding-left:7px;}
          
          #msgcontent {display:block; 
          background: #D6D6D6; 
          border:2px solid #F06; 
          border-left:none; 
          padding:5px; 
          min-width:192px; 
          max-width:192px;}
          
          /*Contact form labels*/
          
          /*Contact form inputs*/
          .form input:focus, .form textarea:focus { background-color: #EBEBEB;}
          
          /*Contact form text fields*/
          .form input { 
          font-family:Arial, Helvetica, sans-serif;
          font-size: 80%;
          background-color: #D6D6D6;
          /*border:1px solid #aaa;*/ 
          height:20px; 
          width:180px; 
          margin: 0px;
          padding:2px 5px;
          border-radius: 2px;
          -moz-border-radius: 2px;
          -webkit-border-radius: 2px;}
          /*Contact form text fields*/
          
          /*Contact textarea*/
          .form textarea { font-family:Arial, Helvetica, sans-serif; 
          font-size: 80%;
          width: 240px;
          height: 100px;
          padding: 5px 5px;
          background-color: #D6D6D6;/*padding-right:30px;*/
          /*border:1px solid #aaa;*/
          border-radius: 2px;
          -moz-border-radius: 2px;
          -webkit-border-radius: 2px;}
          /*Contact textarea*/  
          
          /*Contact form inputs*/
          
          /*input/textarea placeholder text*/
          input::-webkit-input-placeholder { color: #777;}
          input:-moz-placeholder { color: #777;}
          ::-webkit-input-placeholder { color: #777;}
          :-moz-placeholder { color: #777;}
          /*input/textarea placeholder text*/
          
          /*sprite email button*/  
          input.submit { width: 148px; 
          height: 40px;
          margin-left: 190px;
          background-position: 0px 0px;
          background-color: transparent; /* or #666*/
          background-image: url(images/email_sprite.png);
          /*background:transparent url(images/email_sprite.png);*/
          text-indent: -9999px;
          display: inline-block; 
          border:none;
          outline:none;} 
          
          input.submit:hover { background-position: 0px -40px;}
          input.submit:active { background-position: 0px -80px;}
          /*sprite email button*/    
          
          .robotic { display:none; }
          
          /*CONTACT FORM - LEFT DIV*/  
        </style>
      </head>
      
      <body>
        <div id="input_wrapper">
          <form name="form" id="form" class="form" action="" onsubmit="return validate(this)" method="post">
            <ul>
              <li>
                <h3>Contact Us</h3>
                <span class="required_notification">* Denotes Required Field</span>
              </li>
              <li>
                <label for="name">Name:</label>
                <input type="text" name="name" id="name" placeholder="Enter your full name *" value="<?php echo htmlspecialchars($nameENT_QUOTES); ?>" />
              </li>
              <li>
                <label for="email">Email:</label>
                <input type="text" name="email" id="email" placeholder="Enter your email address *" value="<?php echo htmlspecialchars($emailENT_QUOTES); ?>"/>
              </li>
              <li>
                <label for="telephone">Phone:</label>
                <input type="text" name="landline" id="landline" placeholder="Enter your landline number *" value="<?php echo htmlspecialchars($landlineENT_QUOTES); ?>"/>
              </li>  
              <li>  
                <label for="mobile">Mobile:</label>
                <input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number *" value="<?php echo htmlspecialchars($mobileENT_QUOTES); ?>"/>
              </li> 
              <li>  
                <label for="message">Message:</label>
                <textarea id="message" name="message" placeholder="Enter your message here...*"><?php echo htmlspecialchars($messageENT_QUOTES); ?></textarea>     
              </li>
              
              <!-- The following field is for robots only, invisible to humans: -->
              <li class="robotic">
                <label for="robotest">If you're human leave this blank:</label>
                <input type="text" id="robotest" name="robotest" class="robotest" />
              </li>  
                      
              <li>
                <input type="hidden" value="s" name="s" />
                <input type="submit" value="submit" class="submit"/>
              </li>
            </ul>
          </form>
        </div>
        
        <script>
          // form validation function //
          function validate(form) {
            var name = form.name.value;
            var email = form.email.value;
            var message = form.message.value;
            var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
            var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
            var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
            if(name == "") {
              inlineMsg('name','Please enter your name!',2);
              return false;
            }
            if(!name.match(nameRegex)) {
              inlineMsg('name','Please enter an invalid name!',2);
              return false;
            }
            if(email == "") {
              inlineMsg('email','<strong>Error!</strong> Please enter your email!',2);
              return false;
            }
            if(!email.match(emailRegex)) {
              inlineMsg('email','<strong>Error!</strong> This email is invalid!',2);
              return false;
            }
            if(message == "") {
              inlineMsg('message','Please enter your message!');
              return false;
            }
            if(message.match(messageRegex)) {
              inlineMsg('message','This message is invalid!');
              return false;
            }
            return true;
          }
          
          // START OF MESSAGE SCRIPT //
          
          var MSGTIMER = 20;
          var MSGSPEED = 5;
          var MSGOFFSET = 3;
          var MSGHIDE = 3;
          
          // build out the divs, set attributes and call the fade function //
          function inlineMsg(target,string,autohide) {
            var msg;
            var msgcontent;
            if(!document.getElementById('msg')) {
              msg = document.createElement('div');
              msg.id = 'msg';
              msgcontent = document.createElement('div');
              msgcontent.id = 'msgcontent';
              document.body.appendChild(msg);
              msg.appendChild(msgcontent);
              msg.style.filter = 'alpha(opacity=0)';
              msg.style.opacity = 0;
              msg.alpha = 0;
            } else {
              msg = document.getElementById('msg');
              msgcontent = document.getElementById('msgcontent');
            }
            msgcontent.innerHTML = string;
            msg.style.display = 'block';
            var msgheight = msg.offsetHeight;
            var targetdiv = document.getElementById(target);
            targetdiv.focus();
            var targetheight = targetdiv.offsetHeight;
            var targetwidth = targetdiv.offsetWidth;
            var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
            var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
            msg.style.top = topposition + 'px';
            msg.style.left = leftposition + 'px';
            clearInterval(msg.timer);
            msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
            if(!autohide) {
              autohide = MSGHIDE;  
            }
            window.setTimeout("hideMsg()", (autohide * 1000));
          }
          
          // hide the form alert //
          function hideMsg(msg) {
            var msg = document.getElementById('msg');
            if(!msg.timer) {
              msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
            }
          }
          
          // face the message box //
          function fadeMsg(flag) {
            if(flag == null) {
              flag = 1;
            }
            var msg = document.getElementById('msg');
            var value;
            if(flag == 1) {
              value = msg.alpha + MSGSPEED;
            } else {
              value = msg.alpha - MSGSPEED;
            }
            msg.alpha = value;
            msg.style.opacity = (value / 100);
            msg.style.filter = 'alpha(opacity=' + value + ')';
            if(value >= 99) {
              clearInterval(msg.timer);
              msg.timer = null;
            } else if(value <= 1) {
              msg.style.display = "none";
              clearInterval(msg.timer);
            }
          }
          
          // calculate the position of the element in relation to the left of the browser //
          function leftPosition(target) {
            var left = 0;
            if(target.offsetParent) {
              while(1) {
                left += target.offsetLeft;
                if(!target.offsetParent) {
                  break;
                }
                target = target.offsetParent;
              }
            } else if(target.x) {
              left += target.x;
            }
            return left;
          }
          
          // calculate the position of the element in relation to the top of the browser window //
          function topPosition(target) {
            var top = 0;
            if(target.offsetParent) {
              while(1) {
                top += target.offsetTop;
                if(!target.offsetParent) {
                  break;
                }
                target = target.offsetParent;
              }
            } else if(target.y) {
              top += target.y;
            }
            return top;
          }
          
          // preload the arrow //
          if(document.images) {
            arrow = new Image(7,80); 
            arrow.src = "images/msg_arrow.gif"; 
          }
        </script>
      </body>
    </html>

  20. #20
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Vielen dank, muchas gracias, merci beaucoup, grazie mille, tack sa mycket! I use to pick up languages fairly well when I lived abroad... lets hope its the same with computer languages.

    I swapped this:
    PHP Code:
    header("location: your-contact-form-address.php?success=1"); 
    for this:
    PHP Code:
    header("location: http://localhost/projects/contact.php?success=1"); 
    On submitting the new form it appears to redirect on itself which is http://localhost:8888

    However test emails fail to send, which is odd as the previous form still works.


    As I already have styled Javascript validation messages are you referring to your code:
    PHP Code:
    if ($_GET['success']){
             echo(
    "Message sent successfully"); 

    If I have to style the success message would my very first attempt at PHP work work?:
    PHP Code:
    if ($_GET['success']){
               echo 
    '<div class="msg success">'.$success.'</div>';
        }
    ?> 
    Sorry if I sound dum! Although I was good a maths so can't be that dense... maybe my mental capacity has slowed down as I've grown older.

  21. #21
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Gern geschehen, Con mucho gusto! De rien! Prego! and Ingen orsak! (in that order )

    Quote Originally Posted by designclash View Post
    I swapped this:
    PHP Code:
    header("location: your-contact-form-address.php?success=1"); 
    for this:
    PHP Code:
    header("location: http://localhost/projects/contact.php?success=1"); 
    On submitting the new form it appears to redirect on itself which is http://localhost:8888

    However test emails fail to send, which is odd as the previous form still works.
    Try changing it to:

    PHP Code:
    header("location:" $_SERVER['PHP_SELF'] . "?success=1"); 
    Does that work?

    Quote Originally Posted by designclash View Post
    As I already have styled Javascript validation messages are you referring to your code:
    PHP Code:
    if ($_GET['success']){
             echo(
    "Message sent successfully"); 
    As the form resubmits to itself, you need some way of determining if it is loading for the first time (i.e. a brand new visitor), or if it is loading after a submission (i.e. the visitor has filled out the form and pressed 'send').
    If it is loading for the first time, you obviously want to display just the form and leave it at that.
    However, if the form is loading after the user has pressed 'send', you then need to work out if a mail was sent, or if validation failed, so that you can display a confirmation message or an error message accordingly.
    These are the messages I'm talking about.

    Let's see if we can get the form working properly, first, then you should hopefully see what I mean.
    If it works as it should and sends a mail, you will see a confirmation message printed at the top of the page.

    Regarding the validation messages, you will need to turn off JavaScript to see these.
    Which browser are you using?

    Quote Originally Posted by designclash View Post
    Sorry if I sound dum! Although I was good a maths so can't be that dense... maybe my mental capacity has slowed down as I've grown older.
    No, not at all. We've all got to learn somewhere. I think it's great that you're having a go at this in the first place!

  22. #22
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nothing like learning by jumping in at the deep end.

    It works. Easy fix. I thought I better check the HTML and discovered myScript.php was missing from the action tag of the form.

    Can the contact form div be swapped for new div with the success message in?

    A extremely rough idea of what I'd like to see:
    successpage.jpg

    I'm actually enjoying a new challenge and intend to keep going!

  23. #23
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    I'm afraid that the action tag was intentionally left blank.
    This way the form could submit to itself.


    We will arrive at the point that you can style the "success" page as per your attachment, but, as you said yourself, it is quite a complicated process with several hidden gotchas, so it's best to make sure that everything is working, before heading on to the next step.

    So, I've amended the code.
    Please copy this code into a PHP file (not HTML) on your computer and save it somewhere in the htdocs folder which is accessed by your MAMP server.

    Then change the email address in the following line, to your email address:

    PHP Code:
    $toaddress "your email address here"
    Don't change anything else in the code.

    Then, don't open the file directly in your browser, rather navigate to the file using the correct url.
    For me (on Windows in xampp) this is http://localhost/projects/contact.php

    For you it will be something with localhost:8888 presumably.
    Important: it shouldn't be anything like "file:///Volumes/Pete's%20Backup/Documents/Sites/www.stuartlighting.co.uk/contact13.html"

    If you then fill out the form and submit it, the form should redirect to itself (i.e. effectively re-render itself) and you should see a new message at the very top of the page which reads "Message sent successfully".
    The url (in the address bar) should still be the same, but will have "?success=1" appended to it.

    Is this the case for you?

    Sorry if I'm telling you stuff you already know, but there are so many things that could go wrong along the way, I just want to make sure we're both on the same page.

    Now the code:

    PHP Code:
    <?php
        $name 
    '';
        
    $email =  '';
        
    $landline =  '';
        
    $mobile =  '';
        
    $message =  '';
         
      if (
    $_POST['s'] == 's'){
        
    $name filter_var($_POST['name'],FILTER_SANITIZE_STRING);
        
    $email filter_var($_POST['email'],FILTER_SANITIZE_STRINGFILTER_VALIDATE_EMAIL);
        
    $landline filter_var($_POST['landline'], FILTER_SANITIZE_STRING);
        
    $mobile filter_var($_POST['mobile'], FILTER_SANITIZE_STRING);
        
    $message filter_var($_POST['message'],FILTER_SANITIZE_STRING);
        
    $robotest $_POST['robotest']; 
          
        if(
    $robotest){
          exit(
    "Sorry, we think you're a bot!");
        }
        
        if (empty(
    $name)){
          
    $error .= "You didn't enter a name <br />";
        }
        
        if (empty(
    $email)){
          
    $error .= "You didn't enter an email address <br />";
        } elseif (!
    eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})\.?$"$email)){
          
    $error .= "The email address appears to be invalid <br />";  
        }
        
        if (empty(
    $landline)){
          
    $error .= "You didn't enter a landline number <br />";
        } elseif (!
    eregi("^[0-9()+\s-]+$"$landline)){
          
    $error .= "The landline number can only contain digits, spaces, brackets, plus or minus <br />";  
        }
        
        
    // Optional Field
        
    if (!empty($mobile) && !eregi("^[0-9()+\s-]+$"$mobile)){
          
    $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
        }  
        
        if (empty(
    $message)){
          
    $error .= "You didn't enter a message <br />";
        }
        
        if (empty(
    $error)) {
          
    $toaddress "your email address here";
          
    $fromaddress "From:"$email;
          
          
    $mailcontent "Name: "$name"\n".
                         
    "Email: "$email"\n".
                         
    "Landline: "$landline"\n".
                         
    "Mobile: "$mobile"\n\n".
                         
    $message;  
                                        
          
    mail($toaddress"Website Contact Form"$mailcontent$fromaddress);
          
    header("location:" $_SERVER['PHP_SELF'] . "?success=1");
        } else {
          echo 
    $error;
        }
      }
      
      if (
    $_GET['success']){
        echo(
    "Message sent successfully");
      }
    ?>

    <!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>Pete's Contact Form with jQuery Validation</title>
        <script type="text/javascript" src="js/messages.js"></script>
        <style type="text/css">
          * {font-family: Arial, Helvetica, sans-serif;}
          body { background-color: #999;}
          .form label { font-size: 90%;} 
          .required_notification { font-size: 80%;} 
          
          /*CONTACT FORM - LEFT DIV*/
          #input_wrapper { width: 500px;
          padding: 10px 20px 20px 20px; 
          background: #555;
          background: -moz-linear-gradient(top, #444 0%, #666 50%); /* firefox */
          background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #444), color-stop(50%, #666)); /* webkit */
          border-radius: 3px;
          -moz-border-radius: 3px;
          -webkit-border-radius: 3px;
          -webkit-box-shadow: 0px 2px 2px #333333;
          box-shadow: 0px 2px 2px #333333;}
          
          /*Padding/margins/borders/outlines settings*/
          input, textarea {
          margin: 0;
          padding: 0;
          border: 0;
          outline: none;}
          
          /*Border Bottom*/    
          .form li:first-child, .contact_form li:last-child {
          border-bottom:1px solid #CCC;}
          /*Border Bottom*/  
          
          /*Padding/margins/borders/outlines*/
          
          /*No glowing edges to inputs!!!*/
          *:focus {outline: none;}
          /*No glowing edges to inputs!!!*/
          
          /*Header*/  
          .form h3 {
          margin:0px;
          display: inline;}
          
          .required_notification {
          color: #F06; /*#27AECF*/
          margin:5px 0 0 0; 
          display:inline;
          float:right;}
          /*Header*/  
          
          /*Contact form labels*/
          .form ul {
          width:500px;
          list-style-type:none;
          list-style-position:outside;
          margin:0px;
          padding:0px;}
          
          .form li{
          color:#FFF;
          padding:10px; 
          border-bottom:1px solid #999;
          position:relative;}
          
          .form label {
          width:80px;
          margin-top: 2px;
          display:inline-block;
          float:left;
          padding:3px;}
          
          #msg {display:none; 
          font-size:75%;
          position:absolute; 
          z-index:200; 
          background: url(images/msg_arrow.gif) left center no-repeat; 
          padding-left:7px;}
          
          #msgcontent {display:block; 
          background: #D6D6D6; 
          border:2px solid #F06; 
          border-left:none; 
          padding:5px; 
          min-width:192px; 
          max-width:192px;}
          
          /*Contact form labels*/
          
          /*Contact form inputs*/
          .form input:focus, .form textarea:focus { background-color: #EBEBEB;}
          
          /*Contact form text fields*/
          .form input { 
          font-family:Arial, Helvetica, sans-serif;
          font-size: 80%;
          background-color: #D6D6D6;
          /*border:1px solid #aaa;*/ 
          height:20px; 
          width:180px; 
          margin: 0px;
          padding:2px 5px;
          border-radius: 2px;
          -moz-border-radius: 2px;
          -webkit-border-radius: 2px;}
          /*Contact form text fields*/
          
          /*Contact textarea*/
          .form textarea { font-family:Arial, Helvetica, sans-serif; 
          font-size: 80%;
          width: 240px;
          height: 100px;
          padding: 5px 5px;
          background-color: #D6D6D6;/*padding-right:30px;*/
          /*border:1px solid #aaa;*/
          border-radius: 2px;
          -moz-border-radius: 2px;
          -webkit-border-radius: 2px;}
          /*Contact textarea*/  
          
          /*Contact form inputs*/
          
          /*input/textarea placeholder text*/
          input::-webkit-input-placeholder { color: #777;}
          input:-moz-placeholder { color: #777;}
          ::-webkit-input-placeholder { color: #777;}
          :-moz-placeholder { color: #777;}
          /*input/textarea placeholder text*/
          
          /*sprite email button*/  
          input.submit { width: 148px; 
          height: 40px;
          margin-left: 190px;
          background-position: 0px 0px;
          background-color: transparent; /* or #666*/
          background-image: url(images/email_sprite.png);
          /*background:transparent url(images/email_sprite.png);*/
          text-indent: -9999px;
          display: inline-block; 
          border:none;
          outline:none;} 
          
          input.submit:hover { background-position: 0px -40px;}
          input.submit:active { background-position: 0px -80px;}
          /*sprite email button*/    
          
          .robotic { display:none; }
          
          /*CONTACT FORM - LEFT DIV*/  
        </style>
      </head>
      
      <body>
        <div id="input_wrapper">
          <form name="form" id="form" class="form" action="" onsubmit="return validate(this)" method="post">
            <ul>
              <li>
                <h3>Contact Us</h3>
                <span class="required_notification">* Denotes Required Field</span>
              </li>
              <li>
                <label for="name">Name:</label>
                <input type="text" name="name" id="name" placeholder="Enter your full name *" value="<?php echo htmlspecialchars($nameENT_QUOTES); ?>" />
              </li>
              <li>
                <label for="email">Email:</label>
                <input type="text" name="email" id="email" placeholder="Enter your email address *" value="<?php echo htmlspecialchars($emailENT_QUOTES); ?>"/>
              </li>
              <li>
                <label for="telephone">Phone:</label>
                <input type="text" name="landline" id="landline" placeholder="Enter your landline number *" value="<?php echo htmlspecialchars($landlineENT_QUOTES); ?>"/>
              </li>  
              <li>  
                <label for="mobile">Mobile:</label>
                <input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number *" value="<?php echo htmlspecialchars($mobileENT_QUOTES); ?>"/>
              </li> 
              <li>  
                <label for="message">Message:</label>
                <textarea id="message" name="message" placeholder="Enter your message here...*"><?php echo htmlspecialchars($messageENT_QUOTES); ?></textarea>     
              </li>
              
              <!-- The following field is for robots only, invisible to humans: -->
              <li class="robotic">
                <label for="robotest">If you're human leave this blank:</label>
                <input type="text" id="robotest" name="robotest" class="robotest" />
              </li>  
                      
              <li>
                <input type="hidden" value="s" name="s" />
                <input type="submit" value="submit" class="submit"/>
              </li>
            </ul>
          </form>
        </div>
        
        <script>
          // form validation function //
          function validate(form) {
            var name = form.name.value;
            var email = form.email.value;
            var message = form.message.value;
            var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
            var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
            var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
            if(name == "") {
              inlineMsg('name','Please enter your name!',2);
              return false;
            }
            if(!name.match(nameRegex)) {
              inlineMsg('name','Please enter an invalid name!',2);
              return false;
            }
            if(email == "") {
              inlineMsg('email','<strong>Error!</strong> Please enter your email!',2);
              return false;
            }
            if(!email.match(emailRegex)) {
              inlineMsg('email','<strong>Error!</strong> This email is invalid!',2);
              return false;
            }
            if(message == "") {
              inlineMsg('message','Please enter your message!');
              return false;
            }
            if(message.match(messageRegex)) {
              inlineMsg('message','This message is invalid!');
              return false;
            }
            return true;
          }
          
          // START OF MESSAGE SCRIPT //
          
          var MSGTIMER = 20;
          var MSGSPEED = 5;
          var MSGOFFSET = 3;
          var MSGHIDE = 3;
          
          // build out the divs, set attributes and call the fade function //
          function inlineMsg(target,string,autohide) {
            var msg;
            var msgcontent;
            if(!document.getElementById('msg')) {
              msg = document.createElement('div');
              msg.id = 'msg';
              msgcontent = document.createElement('div');
              msgcontent.id = 'msgcontent';
              document.body.appendChild(msg);
              msg.appendChild(msgcontent);
              msg.style.filter = 'alpha(opacity=0)';
              msg.style.opacity = 0;
              msg.alpha = 0;
            } else {
              msg = document.getElementById('msg');
              msgcontent = document.getElementById('msgcontent');
            }
            msgcontent.innerHTML = string;
            msg.style.display = 'block';
            var msgheight = msg.offsetHeight;
            var targetdiv = document.getElementById(target);
            targetdiv.focus();
            var targetheight = targetdiv.offsetHeight;
            var targetwidth = targetdiv.offsetWidth;
            var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
            var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
            msg.style.top = topposition + 'px';
            msg.style.left = leftposition + 'px';
            clearInterval(msg.timer);
            msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
            if(!autohide) {
              autohide = MSGHIDE;  
            }
            window.setTimeout("hideMsg()", (autohide * 1000));
          }
          
          // hide the form alert //
          function hideMsg(msg) {
            var msg = document.getElementById('msg');
            if(!msg.timer) {
              msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
            }
          }
          
          // face the message box //
          function fadeMsg(flag) {
            if(flag == null) {
              flag = 1;
            }
            var msg = document.getElementById('msg');
            var value;
            if(flag == 1) {
              value = msg.alpha + MSGSPEED;
            } else {
              value = msg.alpha - MSGSPEED;
            }
            msg.alpha = value;
            msg.style.opacity = (value / 100);
            msg.style.filter = 'alpha(opacity=' + value + ')';
            if(value >= 99) {
              clearInterval(msg.timer);
              msg.timer = null;
            } else if(value <= 1) {
              msg.style.display = "none";
              clearInterval(msg.timer);
            }
          }
          
          // calculate the position of the element in relation to the left of the browser //
          function leftPosition(target) {
            var left = 0;
            if(target.offsetParent) {
              while(1) {
                left += target.offsetLeft;
                if(!target.offsetParent) {
                  break;
                }
                target = target.offsetParent;
              }
            } else if(target.x) {
              left += target.x;
            }
            return left;
          }
          
          // calculate the position of the element in relation to the top of the browser window //
          function topPosition(target) {
            var top = 0;
            if(target.offsetParent) {
              while(1) {
                top += target.offsetTop;
                if(!target.offsetParent) {
                  break;
                }
                target = target.offsetParent;
              }
            } else if(target.y) {
              top += target.y;
            }
            return top;
          }
          
          // preload the arrow //
          if(document.images) {
            arrow = new Image(7,80); 
            arrow.src = "images/msg_arrow.gif"; 
          }
        </script>
      </body>
    </html>

  24. #24
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So to sum it all up.

    Before I had placed the myScript.php in the action tag. The form sent the message and was I redirected to a white page which read "Message sent successfully" and http://localhost:8888/myScript.php?success=1 appeared in the browser URL.

    Ok, so the action tag is now blank again. I already added my email to the $toaddress.

    Rather than preview the browser in Dreamweaver I navigated Safari to location localhost:8888 . The contact form does submit to itself which resets the form but no success message and the URL remains localhost:8888. Alternatively in MAMP I can press the home button which takes me to localhost:8888. Same thing happens

    The directory for the contact form: localhost/contactform3/index.php
    The directory for the php script: localhost/contactform3/myScript.php

  25. #25
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    UK
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    With regard to MAMP I've changed the default folder from htdocs to my localhost folder.

    The htdocs folder is located in the MAMP folder in Applications.

    Will this make any difference?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •