Skip to content
Advertisement

After the user clicks submit, the page goes to the php file. How can it remain on the HTML file and submit the form information to the email?

I am a beginner at PHP and was working on a contact form.

After selecting the submit button, the response message is not shown. The page goes to the PHP file and the email is never sent. Also, none of the error messages appear.

I am using validate.js and Jquery form.js. Here is a reference link:http://www.tutwow.com/htmlcss/create-a-simple-and-secure-contact-form-with-jquery-and-php/

The style of the contact form is similar to the one featured on the Clicky Media page (Click get a quote on the site.) HTML:

<div class='contentform'>

        <form id="contact_form" action="contactform.php" method="post" novalidate="nonvalidate">

<div class="form">
 <select>
  <option value="Select Topic">--Select Topic--</option>
   <option value=""></option>
   <option value=""></option>
   <option value=''></option>

  </select> 

              <input kl_virtual_keyboard_secure_input="on" id="overlay_name" name="overlay_name" value="First Name"  onfocus="if (this.value == 'First Name') {this.value = '';}" onblur="if (this.value == '') {this.value = 'First Name';}" type="text"></input>
    <input kl_virtual_keyboard_secure_input="on" id="overlay_name2" name="overlay_name2" value="Last Name" class="right" onfocus="if (this.value == 'Last Name') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Last Name';}" type="text"></input>
    <input kl_virtual_keyboard_secure_input="on" id="overlay_telephone" name="overlay_telephone" value="Phone" class="left" onfocus="if (this.value == 'Phone') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Phone';}" type="text"></input>
            <input kl_virtual_keyboard_secure_input="on" id="overlay_email" name="overlay_email"  value="Email" class="right" onfocus="if (this.value == 'Email') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Email';}" type="email"></input>



<textarea style="overflow: hidden; word-wrap: break-word; resize: none; height: 27px;" rows="1" id="overlay_message" name="overlay_message" onfocus="if (this.value == 'Message') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Message';}"> Message </textarea>
</div>
  <div class='formfooter'>

  <input id="send" type='submit' name='sumbit' value ='send message'></input>
  </div>
  </form>
        <div id="response"></div>
</div>

Javascript:

$('#contactform').validate({
// Specify what the errors should look like
// when they are dynamically added to the form
errorElement: "input",
errorPlacement: function(error, element) {
  error.insertBefore( element.parent().parent() );
  error.wrap("<input class='ErrorField'></input>");

},

// Add requirements to each of the fields
rules: {
  overlay_name: {
    required: true,
    minlength: 3
  },
  overaly_name2:{
            required:true,
            minlength:3
  },
  overlay_email: {
    required: true,
    email: true
  },
  overlay_telephone:{
            required:true,
            minlength:10,
            expression: "if (VAL != 'Phone') return true; else return false;",

  },
  overlay_message: {
    required: true,
    minlength: 10
  }
},

// Specify what error messages to display
// when the user does something horrid
messages: {
  overlaye_name: {
    required: "Please enter your name.",
    minlength: jQuery.format("At least {0} characters required.")
  },
   overlaye_name2: {
    required: "Please enter your last name.",
    minlength: jQuery.format("At least {0} characters required.")
  },
  overlay_email: {
    required: "Please enter your email.",
    email: "Please enter a valid email."
  },
  overlay_telephone:{
            required:"Please enter telephone number.",
            phone:"Please enter valid number."
  },

  overlay_message: {
    required: "Please enter a message.",
    minlength: jQuery.format("At least {0} characters required.")
  }
},

// Use Ajax to send everything to processForm.php
submitHandler: function(form) {
  $("#send").attr("value", "Sending...");
  $(form).ajaxSubmit({
    target: "#response",
    success: function(responseText, statusText, xhr, $form) {

      $("#response").html(responseText).hide().slideDown("fast");
    }
  });
  return false;
}
});

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["overlay_name"];
  $name2=$_POST["overlay_name2"];
  $telephone=$_POST["overlay_telephone"];
  $email=$_POST["overlay_email"];
   $message=$_POST["overlay_message"];

  // Test input values for errors
  $errors = array();
  if(strlen($name) < 2) {
  if(!$name) {
   $errors[] = "You must enter a name.";
     }    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) < 10) {
        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>");
       }


        $to = "email address here";
        $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;
    } 

Advertisement

Answer

You are not at all connecting your submitHandler with the <form>‘s submit event. Do this:

$(function () {
  $("#contactForm").submit(submitHandler);
});
Advertisement