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.
I would really appreciate if someone could help me.
Thank you!