Stop form page refresing/reloading if captcha is not validated

Hi all,

I’m a beginner to the codding part and I’m trying to stop my form page from refreshing when the submit button is clicked and the captcha box is not checked but I can’t manage to do that.

I’ve managed to make the form work well, have the errors for all fields and also the fields value to be remembered but I can’t stop the page reloading and that is annoying as it goes back to the top of the page.

Any idea what it’s missing or if it’s something not right? Thank you!

This is my html code:

<form method="post"  id="contactform" name="contactform" action="/contact">
<div class="textbox-1"><label for="name">Your Name *</label>
<input class="textbox" type="text" name="name" title=""  value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name'], ENT_QUOTES) : ''; ?>"
                           oninvalid="this.setCustomValidity('Please Enter Your Name')"
                           oninput="setCustomValidity('')" required>
                     </div>
<div class="textbox-1"><label for="email">Your Email *</label>
 <input class="textbox" type="email" name="email" title="" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES) : ''; ?>"
                           oninvalid="this.setCustomValidity('Please Enter a Valid Email Address')"
                           oninput="setCustomValidity('')" required>
                     </div>
<label>How did you hear about us? (Not necessary, but we appreciate the effort.)</label>
 <select name="where" class="dropdown" id="where" title="" >
                        <option value="-">Click to Choose...</option>
                        <option value="Google Search" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Google Search') ? 'selected' : ''; ?>> Google Search </option>
                        <option value="Social Media" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Social Media') ? 'selected' : ''; ?>> Social Media </option>
                        <option value="Forum" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Forum') ? 'selected' : ''; ?>> Forum </option>
                        <option value="Recommendation" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Recommendation') ? 'selected' : ''; ?>> Recommendation </option>
                        <option value="Other" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Other') ? 'selected' : ''; ?>> Other </option><?php echo isset($_POST['where']) ? htmlspecialchars($_POST['where'], ENT_QUOTES) : ''; ?>
                     </select>
<br/><br/>
<label for="message">Your Message *</label>
    <textarea name="message" id="message" class="textarea" type="textarea" title="" oninvalid="this.setCustomValidity('Please Enter Your Message')"
oninput="setCustomValidity('')" required><?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message'], ENT_QUOTES) : ''; ?>
</textarea>
                     <br/><br/>
<label class="container" >
<input name="terms" type="checkbox" <?php 
int !empty($_SESSION['terms']) && $_SESSION['terms'] == true ? 'checked="checked"' : ''; ?>
                        oninvalid="this.setCustomValidity('Please indicate that you have read and accept our Terms of Use and Privacy Policy agreements.')"
                        oninput="setCustomValidity('')" required>
                     </input>
<span> I have read and accept the <a class="content-link2" href="/terms">Terms of Use</a> and <a class="content-link2" href="/privacy">Privacy Policy</a> agreements. *</span>
<span class="checkmark"></span>
</label>
<label class="container">
<input type="checkbox" name="newsletter" id="newsletter" value="yes"  <?php print !empty($_SESSION['newsletter']) && $_SESSION['newsletter'] == true ? 'checked="checked"' : ''; ?>>
 <span>I want to receive e-mails about limited-time special offers.</span>
<span class="checkmark"></span>
</label>
<div class="clr"></div>
<br/>
<div class="h-captcha" name="h-captcha" id="hcaptcha" data-sitekey="key" ></div>                
<?php if(!empty($errMsg)): ?><div class="errMsg" id="errMsg"><?php echo $errMsg; ?></div><?php endif; ?>
<?php if(!empty($succMsg)): ?><div class="succMsg"><?php echo $succMsg; ?></div><?php endif; ?>
<div class="bot-cont"><button type="submit" name="submit" class="submit_button" value="Submit">SUBMIT MESSAGE</button></div>
<br/><br/>
<label>* required fields</label>            
</form>

And this is the php code:

<?php 
 
// hCAPTCHA API key configuration 
$secretKey = 'key'; 
 session_start();
if(!empty($_POST['terms'])) {
    $_SESSION['terms'] = true;
} 
else {
    $_SESSION['terms'] = false;
}
 session_start();
if(!empty($_POST['newsletter'])) {
    $_SESSION['newsletter'] = true;
} 
else {
    $_SESSION['newsletter'] = false;
}

  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 $string_exp = "/^[A-Za-z .'-]+$/";

// If the form is submitted 
if(isset($_POST['submit'])){ 
     
    // Validate form fields 
    if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message'])){ 
         
        // Validate hCAPTCHA checkbox 
        if(!empty($_POST['h-captcha-response'])){ 
            // Verify API URL 
            $verifyURL = 'https://hcaptcha.com/siteverify'; 
             
            // Retrieve token from post data with key 'h-captcha-response' 
            $token = $_POST['h-captcha-response']; 
             
            // Build payload with secret key and token 
            $data = array( 
                'secret' => $secretKey, 
                'response' => $token, 
                'remoteip' => $_SERVER['REMOTE_ADDR'] 
            ); 
             
            // Initialize cURL request 
            // Make POST request with data payload to hCaptcha API endpoint 
            $curlConfig = array( 
                CURLOPT_URL => $verifyURL, 
                CURLOPT_POST => true, 
                CURLOPT_RETURNTRANSFER => true, 
                CURLOPT_POSTFIELDS => $data 
            ); 
            $ch = curl_init(); 
            curl_setopt_array($ch, $curlConfig); 
            $response = curl_exec($ch); 
            curl_close($ch); 
             
            // Parse JSON from response. Check for success or error codes 
            $responseData = json_decode($response); 
             
            // If reCAPTCHA response is valid 
            if($responseData->success){ 
                // Posted form data 
$email_to = "myemail";
    $email_subject = "Email Subject";
    $ip_address=$_SERVER['REMOTE_ADDR'];$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ip_address;$addrDetailsArr=unserialize(file_get_contents($geopluginURL));
    $country=$addrDetailsArr['geoplugin_countryName'];
     $name = $_POST['name']; // required
    $where = $_POST['where']; 
    $email_from = $_POST['email']; // required
    $message = $_POST['message']; // required
    $newsletter = $_POST['newsletter']; 
    $hcaptcha = $_POST['h-captcha']; // required
$terms = $_POST['terms']; // required
 
    $email_message = "Form details below.<br/><br/><br/>\n\n";
   
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
    
    $email_message .= "IP: ".clean_string($ip_address)."<br/><br/>\n\n";
    $email_message .= "Country: ".clean_string($country)."<br/><br/><br/>\n\n";
    $email_message .= "Name: ".clean_string($name)."<br/><br/>\n\n";
    $email_message .= "Heard from: ".clean_string($where)."<br/><br/>\n\n";
    $email_message .= "Email: ".clean_string($email_from)."<br/><br/>\n\n";
    $email_message .= "Newsletter: ".clean_string($newsletter)."<br/><br/>\n";
    $email_message .= "Message: ".clean_string($message)."<br/><br/>\n";

      // Always set content-type when sending HTML email
      $headers = "MIME-Version: 1.0" . "\r\n";
      $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
      // More headers
      $headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
      //send email
@mail($email_to, $email_subject, $email_message, $headers);
    $succMsg = header("location: $site_url/thank-you");
            }else{ 
                $errMsg = 'Verification failed, please try again.'; 
            } 
        }else{ 
            $errMsg = 'Please complete the CAPTCHA.'; 
        } 
    }else{ 
        $errMsg = 'Please complete the CAPTCHA.'; 
    } 
} 
 
?>

I’ve also tried some javascript codes I found online but nothing completely worked.
I’ve spent days trying to make this work and I can’t. :frowning:
I would really appreciate if someone could help me.

Thank you!

Ok, here is the full contact page and the page now doesn’t use any other java script file.
Thank you.

<?php
   $lastModified=filemtime(__FILE__); 
   $etagFile = md5_file(__FILE__); 
   $ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false); 
   $etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false); 
   header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT"); 
   header("ETag: \"$etagFile\""); 
   if (@strtotime($ifModifiedSince)==$lastModified || $etagHeader == $etagFile) { header("HTTP/1.1 304 Not Modified"); exit; };include 'class.phpmailer.php';
   session_start();$page_id=4;
   ?><!DOCTYPE html>
<html lang="en">
   <meta charset=utf-8>
   <title>xxx</title>
   <meta name="description" content="xxx"/>
   <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
   <meta property="fb:page_id" content="xxx"/>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="icon" href="xxx" type="image/ico" title="Favicon Icon"/>
   <link rel="canonical" href="xxx"/>
   <link href="/contact.css" rel="stylesheet"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
   <script src='https://js.hcaptcha.com/1/api.js' async defer></script>
   <link rel="alternate" href="xxx" hreflang="en"/>
   <body>
      <div class="all">
         <header><?php include("top-simple.php");?></header>
         <div class=banner>
            <div id=custom-title>
               <div class="custom3-title">
                  <h1> xxx </h1>
               </div>
               <div class="custom_text4">
                  <p>xxx </p>
               </div>
            </div>
            <div id="contact-us"></div>
         </div>
         <div id="wrapper">
            <div class="list-wrap">
               <div class="content">
<form method="post"  id="contactform" name="contactform" action="/contact">
<div class="textbox-1"><label for="name">Your Name *</label>
<input class="textbox" type="text" name="name" title=""  value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name'], ENT_QUOTES) : ''; ?>"
                           oninvalid="this.setCustomValidity('Please Enter Your Name')"
                           oninput="setCustomValidity('')" required>
                     </div>
<div class="textbox-1"><label for="email">Your Email *</label>
 <input class="textbox" type="email" name="email" title="" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES) : ''; ?>"
                           oninvalid="this.setCustomValidity('Please Enter a Valid Email Address')"
                           oninput="setCustomValidity('')" required>
                     </div>
<label>How did you hear about us? (Not necessary, but we appreciate the effort.)</label>
 <select name="where" class="dropdown" id="where" title="" >
                        <option value="-">Click to Choose...</option>
                        <option value="Google Search" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Google Search') ? 'selected' : ''; ?>> Google Search </option>
                        <option value="Social Media" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Social Media') ? 'selected' : ''; ?>> Social Media </option>
                        <option value="Forum" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Forum') ? 'selected' : ''; ?>> Forum </option>
                        <option value="Recommendation" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Recommendation') ? 'selected' : ''; ?>> Recommendation </option>
                        <option value="Other" <?php echo (isset($_POST['where']) && $_POST['where'] === 'Other') ? 'selected' : ''; ?>> Other </option><?php echo isset($_POST['where']) ? htmlspecialchars($_POST['where'], ENT_QUOTES) : ''; ?>
                     </select>
<br/><br/>
<label for="message">Your Message *</label>
    <textarea name="message" id="message" class="textarea" type="textarea" title="" oninvalid="this.setCustomValidity('Please Enter Your Message')"
oninput="setCustomValidity('')" required><?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message'], ENT_QUOTES) : ''; ?>
</textarea>
                     <br/><br/>
<label class="container" >
<input name="terms" type="checkbox" <?php 
int !empty($_SESSION['terms']) && $_SESSION['terms'] == true ? 'checked="checked"' : ''; ?>
                        oninvalid="this.setCustomValidity('Please indicate that you have read and accept our Terms of Use and Privacy Policy agreements.')"
                        oninput="setCustomValidity('')" required>
                     </input>
<span> I have read and accept the <a class="content-link2" href="/terms">Terms of Use</a> and <a class="content-link2" href="/privacy">Privacy Policy</a> agreements. *</span>
<span class="checkmark"></span>
</label>
<label class="container">
<input type="checkbox" name="newsletter" id="newsletter" value="yes"  <?php print !empty($_SESSION['newsletter']) && $_SESSION['newsletter'] == true ? 'checked="checked"' : ''; ?>>
 <span>I want to receive e-mails about limited-time special offers.</span>
<span class="checkmark"></span>
</label>
<div class="clr"></div>
<br/>
<div class="h-captcha" name="h-captcha" id="hcaptcha" data-sitekey="key" ></div>                
<?php if(!empty($errMsg)): ?><div class="errMsg" id="errMsg"><?php echo $errMsg; ?></div><?php endif; ?>
<?php if(!empty($succMsg)): ?><div class="succMsg"><?php echo $succMsg; ?></div><?php endif; ?>
<div class="bot-cont"><button type="submit" name="submit" class="submit_button" value="Submit">SUBMIT MESSAGE</button></div>
<br/><br/>
<label>* required fields</label>            
</form>
</div>
            </div>
         </div>
         <footer><?php include("bot.php");?></footer>
      </div>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.