You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为订阅按钮添加Invisible ReCaptcha后弹窗提示失效问题求助

Hey there, let's fix that popup issue while keeping the Invisible ReCaptcha working! Here's what's going wrong and how to get things back to normal:

The Root Problem

Your original form used AJAX (likely powered by a plugin tied to the data-success attribute) to submit without page reloads and show the popup. But after adding ReCaptcha, you're using document.getElementById("newsletter").submit() which triggers a standard form submission—this loads the PHP script directly instead of triggering the frontend success popup.

Step-by-Step Fix

We'll adjust the frontend to use AJAX for submission (so we can keep the popup) and add critical server-side ReCaptcha validation (you were missing this before—frontend ReCaptcha alone isn't enough to block bots!).

1. Update the Frontend JavaScript

Replace your existing ReCaptcha script with this code. It uses fetch to submit the form via AJAX, then triggers the toastr popup just like before:

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function onSubmit(token) {
  const form = document.getElementById("newsletter");
  const formData = new FormData(form);

  // Submit form via AJAX instead of page reload
  fetch(form.action, {
    method: form.method,
    body: formData
  })
  .then(response => {
    if (response.ok) {
      // Show the success popup using toastr (matches your original setup)
      toastr.success(form.dataset.success, '', {
        positionClass: form.dataset.toastrPosition
      });
      // Reset the form for future submissions
      form.reset();
    } else {
      toastr.error("Oops, something went wrong. Please try again later.");
    }
  })
  .catch(() => {
    toastr.error("Network error—check your connection and try again.");
  });
}
</script>

Note: Make sure your page still loads the toastr CSS/JS (you had this before, since the popup worked pre-ReCaptcha). If not, add these links to your page head:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

2. Add Server-Side ReCaptcha Validation to PHP

Your original PHP script didn't validate the ReCaptcha token—bots could bypass the frontend check! Update your newsletter.php with this code (replace your_recaptcha_secret_key with the secret key from your Google ReCaptcha dashboard):

<?php
/**
 * @version v1.0.0
 * @author
 * @date Saturday, April 9, 2016
 **/
date_default_timezone_set('Etc/UTC');
@ini_set('display_errors', 0);
@ini_set('track_errors', 0);

// 1. Validate ReCaptcha first (critical for blocking bots)
$recaptchaSecret = "your_recaptcha_secret_key"; // Replace with your actual secret key
$recaptchaToken = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : '';

$recaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify';
$recaptchaData = [
    'secret' => $recaptchaSecret,
    'response' => $recaptchaToken,
    'remoteip' => $_SERVER['REMOTE_ADDR']
];

$recaptchaOptions = [
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($recaptchaData)
    ]
];

$recaptchaContext = stream_context_create($recaptchaOptions);
$recaptchaResult = file_get_contents($recaptchaUrl, false, $recaptchaContext);
$recaptchaResponse = json_decode($recaptchaResult);

if (!$recaptchaResponse->success) {
    http_response_code(400);
    echo json_encode(['error' => 'ReCaptcha verification failed']);
    exit;
}

// 2. Validate email and write to file (original logic)
$array['email'] = isset($_REQUEST['email']) ? ckmail($_REQUEST['email']) : false;
if($array['email'] !== false) {
    $fh = fopen('_newsletter.txt', 'a+');
    fwrite($fh, "\r\n" . $array['email']);
    fclose($fh);
    unset($fh, $array);
    
    // Return success response to frontend
    http_response_code(200);
    echo json_encode(['success' => true]);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid email format']);
}

/************************************
@CHECK EMAIL
/************************************/
function ckmail($email) {
    $email = trim(strtolower($email));
    if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/',trim($email))){
        return $email;
    } else {
        return false;
    }
}
?>

What This Does

  • No more page reload: The AJAX submission keeps users on your site after clicking Subscribe.
  • Restores the success popup: We explicitly trigger toastr with your original success message and position.
  • Blocks bots properly: Server-side ReCaptcha validation ensures only real humans get their emails added to your list.

内容的提问来源于stack exchange,提问作者Dan Graves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:40:07