0

I was working on contactus.php form. I am not testing whether the email will be sent to our account. However, my objective is when the form is invalid, it will reload the page and redirect user back to the same page while if the form is valid, it will redirect user to contactthanks.php

What is it that I am missing in the code? Aside of that, i unsure what when wrong that my form is always showing invalid form?

contactus.php

    <form name="contactForm" method="post" id="contactForm"
                    onsubmit="return chkContact(this)">
                    <div class='input1'>
                        <div class="help">
                            <input id="name" name="name" type="text" placeholder="Name "
                                value="<?php echo $user_profile["name"]; ?>">
                        </div>

                        <div id="email-label" class="help">
                            <input id="email" name="email" type="text"
                                placeholder="Email Address " class="input-xlarge"
                                value="<?php echo $user_profile["name"]; ?>">
                        </div>

                        <div id="subj-label" class="help">
                            <input id="subject" name="subject" type="text"
                                placeholder="Subject " class="input-xlarge"
                                value="<?php echo $user_profile["subject"]; ?>">
                        </div>
                        <div id="message" class="help">
                            <textarea id="message" name="message" rows="13" cols="33"
                                placeholder="Message " class="input-xlarge"></textarea>
                        </div>

                        <button id="btnSubmit" type="submit" value="Send"
                            onclick="return chkContact()">Send</button>
                        <div id="msgSubmit" class="h3 text-center hidden"></div>
                    </div>
                </form>
<script>
function chkContact(form) {
    if(form.name.value == "" && form.email.value == "" && form.subject.value == "" && form.message.value == "" ) {
          alert("Please fill in the required fields: \n\u26AC Name \n\u26AC Email \n\u26AC Subject \n\u26AC Message");
             form.name.focus();
             return false;
    }
     if(form.name.value == "") {
         alert("Error: Name cannot be blank!");
         form.name.focus();
         return false;
       }

     if(form.email.value == "") {
         alert("Error: Email Address cannot be blank!");
         form.email.focus();
         return false;
       }
       re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
       if(!re.test(form.email.value)) {
         alert("Error: Invalid email address!");
         form.email.focus();
         return false;
       }
       if(form.subject.value == "") {
             alert("Error: Subject cannot be blank!");
             form.subject.focus();
             return false;
       }
       if(form.message.value == "") {
             alert("Error: Message cannot be blank!");
             form.message.focus();
             return false;
       }
    var name = document.getElementById('name').value;
    var email = document.getElementById('email').value;
    var subject = document.getElementById('subject').value;
    var message = document.getElementById('message').value;
    var dataString='name='+ name+'&email='+email+'&subject='+subject+'&message='+message;

    $.ajax({
        type:"post",
        url: "<?php echo $base_url; ?>ajax-helper/post-email.php",
        data:dataString,
        cache:false,
        success: function(data){
        if (/^\s*SUCCESS\s*$/.test(data)) {
        window.location = '<?php echo $base_url; ?>index?success=true';
           }
        else{
             alert(data);
          }
        }
    });
        return false;
}
</script>

post-email.php

 <?php
// session_start ();
include_once ('functions.php');
include ('php-header.php');

$EmailTo = "emailaddress@test.com";
$Subject = "New Message Received";

$name = Trim ( stripslashes ( $_POST ['name'] ) );
$email = Trim ( stripslashes ( $_POST ['email'] ) );
$subject = Trim ( stripslashes ( $_POST ['subject'] ) );
$message = Trim ( stripslashes ( $_POST ['message'] ) );

// prepare email body text
$Body = "<br>";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n<br>";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n<br>";
$Body .= "Subject: ";
$Body .= $subject;
$Body .= "\n<br>";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n<br>";

// send email
$url = '..';
$fields = array (
'BASE_URL' => $base_url,
'BRAND_NAME' => $PROJECT_NAME,
'RECEIVER_EMAIL' => $EmailTo,
'SENDER_EMAIL' => $email,
'RECEIVER_NAME' => '..',
'SENDER_NAME' => $name,
'SUBJECT' => $subject,
'CONTENT' => $Body
);

$success = mail ( $EmailTo, $Subject, $Body, "From: <$email>" );

// $success = mail ( $EmailTo, $Subject, $Body, "From:" . $email );
$fields_string = json_encode ( $fields );
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );

curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );

curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, count ( $fields ) );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields_string );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
'Content-Type: application/json',
'Content-Length: ' . strlen ( $fields_string )
) );
$result = curl_exec ( $ch );
curl_close ( $ch );

if ($success) {
    echo "Message sent";
} else {
    echo "Message not sent! Try again.";
}
?>

contactthanks.php

<?php
include ('includes/header.php');
include ('includes/header-search.php');
include ('includes/header-nav.php');
include ('includes/header-info.php');
?>

<!DOCTYPE html>
<html lang="en">
<body id="contactus">
    <div class="container">
        <div class="row">
            <div class="one-half column"
                style="background-image: url(images/abtus.png); background-repeat: none;">
                <div class="txt-header" style="margin: 40px 40px;">
                    <div class="about_heading">Contact Us</div>
                    <div class="about_heading-txt">Send us a Message</div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="eleven columns" style="padding-bottom: 5%;">
                <div class="google-maps">
                    <iframe width="640" height="450" frameborder="0" style="border: 0"
                        src="https://www.google.com/maps/embed/v1/place?key=AIzaSyAKR7iBlBCPxntB3a6OV7hTeCQpdL9f9Yk
      &q=Rochestor+Mall
      &attribution_source=Google+Maps+Embed+API
      &attribution_web_url=http://www.rochestermall.com.sg/
      &attribution_ios_deep_link_id=comgooglemaps://?daddr=Rochestor+Mall"
                        allowfullscreen> </iframe>
                </div>
            </div>
            <div class="six columns">
                <h3>Your message has been sent!</h3>
                <p>
                    <a href="contactus.php" style="float: right; margin: 5%;">&#9668;
                        Back to Contact Form</a>
                </p>
            </div>
        </div>
    </div>
</body>
</html>
<?php
include ('includes/footer.php');
?>

closed as off-topic by fuxia Jan 7 '16 at 9:00

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • What's it ? Is for a plugin or ... ? If it's a contact form that not related to wordpress why ask this question here? – Daniel Noaein Dec 21 '15 at 7:39
  • Whats going here :0 – daniyalahmad Dec 21 '15 at 8:32
  • i must have mistaken it by clicking on the wrong tag. apologise for that. will update it – SitiNuraini Yakob Dec 21 '15 at 8:34
1

You should remove the

<meta http-equiv=\"refresh\" content=\"0;URL=contactus.php\">

from your document head section, first.

The problem

Each time you press submit button on your form, you call chkContact where you do an ajax call. You should put an if before the ajax, so that it would not get executed if the form is invalid.

if( form is valid ){
    $.ajax( ... );
}else{
    prompt the user that form is invalid and should be filled again
}

Update

<form name="contactForm" method="post" id="contactForm" onsubmit="return chkContact(this)">
  <div class='input1'>
    <div class="help">
      <input id="name" name="name" type="text" placeholder="Name " value="<?php echo $user_profile["name"]; ?>">
     </div>
     <div id="email-label" class="help">
       <input id="email" name="email" type="text" placeholder="Email Address " class="input-xlarge" value="<?php echo $user_profile["name"]; ?>">
     </div>
     <div id="subj-label" class="help">
       <input id="subject" name="subject" type="text" placeholder="Subject " class="input-xlarge" value="<?php echo $user_profile["subject"]; ?>">
      </div>
      <div id="message" class="help">
         <textarea id="message" name="message" rows="13" cols="33" placeholder="Message " class="input-xlarge"></textarea>
      </div>
      <button id="btnSubmit" type="submit" value="Send" onclick="return chkContact()">Send</button>
    <div id="msgSubmit" class="h3 text-center hidden"></div>
  </div>
</form>
<script>
  function chkContact(form){
    if(form.name.value == "" && form.email.value == "" && form.subject.value == "" && form.message.value == "" ){
      alert("Please fill in the required fields: \n\u26AC Name \n\u26AC Email \n\u26AC Subject \n\u26AC Message");
      form.name.focus();
      return false;
    }
    if(form.name.value == ""){
      alert("Error: Name cannot be blank!");
      form.name.focus();
      return false;
    }
    if(form.email.value == ""){
      alert("Error: Email Address cannot be blank!");
      form.email.focus();
      return false;
    }
    re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
     if(!re.test(form.email.value)){
       alert("Error: Invalid email address!");
       form.email.focus();
       return false;
    }
    if(form.subject.value == ""){
      alert("Error: Subject cannot be blank!");
      form.subject.focus();
      return false;
    }
    if(form.message.value == ""){
      alert("Error: Message cannot be blank!");
      form.message.focus();
      return false;
    }

    var name = document.getElementById('name').value;
    var email = document.getElementById('email').value;
    var subject = document.getElementById('subject').value;
    var message = document.getElementById('message').value;
    var dataString='name='+ name+'&email='+email+'&subject='+subject+'&message='+message;

    $.ajax({
      type:"post",
      url: "<?php echo $base_url; ?>ajax-helper/post-email.php",
      data:dataString,
      cache:false,
      success: function(data){
        if (/^\s*SUCCESS\s*$/.test(data)) {
          window.location = '<?php echo $base_url; ?>index?success=true';
        }else{
          alert(data);
        }
      }
    });

    return false;
  }
</script>
  • Thankyou for the reply. what do you mean by "put an if before the ajax, so that it would not get executed if the form is invalid" Do you have an example which i can refer? @Trix – SitiNuraini Yakob Dec 21 '15 at 8:15
  • I am editing my answer so to be more clear in this case. check in a minute – Pmpr Dec 21 '15 at 8:24
  • alright sure :) – SitiNuraini Yakob Dec 21 '15 at 8:29
  • based on what you've updated, the if statement only handle the ajax? not quite sure on how i should update my ajax based on what i've added in my post above – SitiNuraini Yakob Dec 21 '15 at 8:48
  • Please edit your question and remove the `` and `` files, as they are not the cause of your problem. Just keep the first snippet. I will add some more clarification to my answer – Pmpr Dec 21 '15 at 8:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.