The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> hCaptcha - How to stop page from refreshing on submit if captcha is not checked/validated
vld1
post Aug 29 2023, 07:10 AM
Post #1





Group: Members
Posts: 3
Joined: 29-August 23
Member No.: 29,037



Hi all,

I have installed hCaptcha into my contact form and it works fine (email is sent only after captcha is checked/validated but how do I stop the page from refreshing on submit if captcha is not checked/validated because all fields value disappear and that is bad for user? Does someone know how I can stop this and just have a popup/text near the captcha to let the user know that is required.

Thank you!


CODE
<?php
if(isset($_POST['submit'])):
    if(isset($_POST['h-captcha-response']) && !empty($_POST['h-captcha-response'])):
        // get verify response
        $data = array(
          'secret' => "code",
          'response' => $_POST['h-captcha-response']
            
          ));


        $verify = curl_init();
        curl_setopt($verify, CURLOPT_URL,   "https://hcaptcha.com/siteverify");
        curl_setopt($verify, CURLOPT_POST, true);
        curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
        $verifyResponse = curl_exec($verify);        
    $responseData = json_decode($verifyResponse);    
        if($responseData->success):
      //contact form submission code
    $email_to = "email";
    $email_subject = "title;
    $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

    $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:/contact-thank-you");
        endif;
    endif;
endif;
?>


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=""
                           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=""
                           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"> Google Search </option>
                        <option value="Bing Search"> Bing Search </option>
                        <option value="Other Search Engine"> Other Search Engine </option>
                        <option value="Social Media"> Social Media </option>
                        <option value="Blog"> Blog </option>
                        <option value="Q&A Websites"> Q&A Websites </option>
                        <option value="Forum"> Forum </option>
                        <option value="Recommendation"> Recommendation </option>
                        <option value="Other"> Other </option>
                     </select>
                     <br/><br/>
                     <label for="message">Your Message *</label>
                     <textarea name="message" class="textarea" type="textarea" title=""
                        oninvalid="this.setCustomValidity('Please Enter Your Message')"
                        oninput="setCustomValidity('')" required>
</textarea>
                     <br/><br/>
                     <label class="container">
                     <input type="checkbox"  value=""
                        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>
                    
                     </label>
                     <label class="container">
                     <input type="checkbox" name="newsletter" id="newsletter" value="yes">
                     <span>I want to receive e-mails about limited-time special offers.</span>
                    
                     </label>
                     <div class="clr"></div>
                     <br/>
                   <div class="h-captcha" data-sitekey="code" ></div>
                  
                     <div class="bot-cont"><button type="submit" name="submit" class="submit_button" value="Submit">SUBMIT MESSAGE</button></div>
                     <br/><br/>
                  </form>


This post has been edited by vld1: Aug 29 2023, 07:24 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 29 2023, 10:09 AM
Post #2


.
********

Group: WDG Moderators
Posts: 9,661
Joined: 10-August 06
Member No.: 7



When the PHP script runs on the server the form has already been submitted, so at that point you may have to let the PHP script repopulate the form fields again with the data the user submitted.

Or you may use the javascript onsubmit event combined with "return false" to prevent the form from submitting (here's a basic example). But then the javascript needs to know if the CAPTCHA has been solved. It appears to me that the CAPTCHA script creates a form field with the NAME "h-captcha-response", maybe you could let the javascript check that this field is not empty.

But see also Bots are better than humans at cracking ‘Are you a robot?’ Captcha tests, study finds . wacko.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
vld1
post Aug 29 2023, 01:19 PM
Post #3





Group: Members
Posts: 3
Joined: 29-August 23
Member No.: 29,037



Hi,

Thank you for your reply. I tried the method from the example you gave but it doesn't work.

I tried another one:

Added an element to display an error message:
CODE
<div id="captcha-error" style="color: red;"></div>


Added an onsubmit attribute to form element :
CODE
<form method="post" id="contactform" name="contactform" action="/contact" onsubmit="return validateForm()">


and a java script:
CODE
<script>
function validateForm() {
    var captcha = document.querySelector('.h-captcha');

    if (!captcha.hasAttribute('data-h-captcha-response')) {
        document.getElementById('captcha-error').textContent = "Please complete the captcha.";
        return false; // Prevent form submission
    }

    var response = captcha.getAttribute('data-h-captcha-response');
    if (response === '') {
        document.getElementById('captcha-error').textContent = "Please complete the captcha.";
        return false; // Prevent form submission
    }

    document.getElementById('captcha-error').textContent = ''; // Clear any previous error
    return true; // Allow form submission
}
</script>


This one didn't work as well.
Yes , the form fields values remain, the error appears but it also appears when the hcaptcha is checked and I try to submit the form, so the error appears no matter if the hcaptcha is checked or not and because of that it doesn't allow the form to be submitted.

I'm a beginner to the codding stuff so I don't know what else I should do.
I want to add a captcha because I have many spam emails and I want to eliminate as many as I can.

Thanks.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 29 2023, 06:06 PM
Post #4


.
********

Group: WDG Moderators
Posts: 9,661
Joined: 10-August 06
Member No.: 7



QUOTE(vld1 @ Aug 29 2023, 08:19 PM) *

CODE
<script>
function validateForm() {
    var captcha = document.querySelector('.h-captcha');

    if (!captcha.hasAttribute('data-h-captcha-response')) {
        document.getElementById('captcha-error').textContent = "Please complete the captcha.";
        return false; // Prevent form submission
    }

    var response = captcha.getAttribute('data-h-captcha-response');
    if (response === '') {
        document.getElementById('captcha-error').textContent = "Please complete the captcha.";
        return false; // Prevent form submission
    }

    document.getElementById('captcha-error').textContent = ''; // Clear any previous error
    return true; // Allow form submission
}
</script>


The above looks like the function ends with "return true" regardless of the previous IF conditions. Try something like this instead:

CODE
function validateForm()
{
    var captcha = document.querySelector('.h-captcha');
    if(!captcha.hasAttribute('data-h-captcha-response') || captcha.getAttribute('data-h-captcha-response')==='')
    {
        document.getElementById('captcha-error').textContent = "Please complete the captcha.";
        return false;
    }
    else
    {
        return true;
    }
}



QUOTE

This one didn't work as well.
Yes , the form fields values remain, the error appears but it also appears when the hcaptcha is checked and I try to submit the form, so the error appears no matter if the hcaptcha is checked or not and because of that it doesn't allow the form to be submitted.

Have you checked that this attribute:

CODE
captcha.getAttribute('data-h-captcha-response')

exists and has a value? You could test that with alertboxes in the javascript.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
vld1
post Aug 29 2023, 06:23 PM
Post #5





Group: Members
Posts: 3
Joined: 29-August 23
Member No.: 29,037



Thank you. Added the java you gave but still the same thing as with the previous java, the error appears but it also appears when the hcaptcha is checked and I try to submit the form, so the error appears no matter if the hcaptcha is checked or not and because of that it doesn't allow the form to be submitted.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 29 2023, 09:02 PM
Post #6


.
********

Group: WDG Moderators
Posts: 9,661
Joined: 10-August 06
Member No.: 7



Check that the DIV element with the CLASS "h-captcha" really got the attribute "data-h-captcha-response" that the javascript is looking for:

CODE
function validateForm()
{
    var captcha = document.querySelector('.h-captcha');
    alert(captcha.outerHTML);
    if(!captcha.hasAttribute('data-h-captcha-response') || captcha.getAttribute('data-h-captcha-response')==='')
    {
        document.getElementById('captcha-error').textContent = "Please complete the captcha.";
        return false;
    }
    else
    {
        return true;
    }
}

The alertbox should show something like

CODE
<div class="h-captcha" data-h-captcha-response="x"></div>

where "x" is whatever value the CAPTCHA script has given it.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Darin McGrew
post Sep 3 2023, 09:52 PM
Post #7


WDG Member
********

Group: Root Admin
Posts: 8,365
Joined: 4-August 06
From: Mountain View, CA
Member No.: 3



QUOTE
Added the java you gave but still the same thing as with the previous java
Note that Java and JavaScript are completely different things. What you've got is JavaScript, not Java.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 28th April 2024 - 09:31 AM