In website operation, the message and comment functions are important channels for interacting with users and collecting feedback.However, this is often accompanied by the problem of spam and malicious flooding.In order to effectively filter out unnecessary content, enabling the captcha mechanism has become a simple and efficient solution.AnQiCMS (AnQiCMS) provides us with a flexible way to easily integrate captcha functionality into comment or message forms.

Next, we will learn in detail how to enable and display the captcha in Anqi CMS.

Step 1: Enable the captcha function in the management background.

First, we need to activate the captcha feature in the Anqi CMS management background. This is the foundation to ensure that the front-end captcha can work normally.

  1. Log in to your Anqi CMS management background.
  2. Find "Function Management" in the left navigation menu and click "Website Message".
  3. On the website message management interface, you will see an option named "Turn on captcha for comments or reviews".Make sure this option is checked or set to 'On' status, and save your settings.

This operation informs the system that a captcha verification is required when the user submits a message or comment.

Second step: Modify the front-end template, integrate captcha display

After enabling the background function, we need to add the corresponding code to the front-end form template of the website's message or comment form so that users can see the captcha image and enter the captcha.This requires us to make some modifications to the template file.

The template files of AnQi CMS are usually located/templateUnder the directory, specific to the comment or review form, you may need to look for similarguestbook/index.htmlorcomment/list.htmlSuch a file, the specific file name may vary depending on the template you are using. Find the form (usually starting with<form>tag) at the location and add the following code snippet.

Sample HTML structure and JavaScript code

In order to make the captcha image refresh dynamically and include the correct captcha identifier when submitted, you can add the following HTML structure in the appropriate position in the form (for example, before the submit button):

<div style="display: flex; clear: both; align-items: center; gap: 10px;">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" class="form-control" style="flex: 1; height: 40px; line-height: 40px; padding: 0 10px; border: 1px solid #ddd;">
  <img src="" id="get-captcha" alt="验证码" style="width: 120px; height: 40px; cursor: pointer; border: 1px solid #ddd;">
</div>

<script>
  // 纯JavaScript方式刷新验证码
  document.getElementById('get-captcha').addEventListener("click", function () {
    fetch('/api/captcha')
      .then(response => response.json())
      .then(res => {
        document.getElementById('captcha_id').value = res.data.captcha_id;
        document.getElementById('get-captcha').src = res.data.captcha;
      })
      .catch(err => {
        console.error('获取验证码失败:', err);
      });
  });
  // 页面加载时自动获取一次验证码
  document.getElementById('get-captcha').click();
</script>

The Simplified Way to Use jQuery

If your website has already included the jQuery library, you can use a more concise jQuery syntax to implement the same captcha refresh function:

<div style="display: flex; clear: both; align-items: center; gap: 10px;">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" class="form-control" style="flex: 1; height: 40px; line-height: 40px; padding: 0 10px; border: 1px solid #ddd;">
  <img src="" id="get-captcha" alt="验证码" style="width: 120px; height: 40px; cursor: pointer; border: 1px solid #ddd;">
</div>

<script>
  // jQuery方式刷新验证码
  $('#get-captcha').on("click", function () {
    $.get('/api/captcha', function(res) {
      $('#captcha_id').val(res.data.captcha_id);
      $('#get-captcha').attr("src", res.data.captcha);
    }, 'json').fail(function(jqXHR, textStatus, errorThrown) {
      console.error('获取验证码失败:', textStatus, errorThrown);
    });
  });
  // 页面加载时自动获取一次验证码
  $('#get-captcha').click();
</script>

Code analysis:

  • <input type="hidden" name="captcha_id" id="captcha_id">This is a hidden field used to store the unique ID generated for each captcha.This ID is sent to the backend along with the user's form submission to match the entered captcha for correctness.
  • <input type="text" name="captcha" required placeholder="请填写验证码" ...>This is the text box for entering the user's input captcha.
  • <img src="" id="get-captcha" alt="验证码" ...>This is the position where the captcha image is displayed. We dynamically set it using JavaScriptsrcProperty.
  • JavaScript code block:
    • It is first set throughdocument.getElementById('get-captcha').addEventListener("click", ...)(Pure JS) or$('#get-captcha').on("click", ...)(jQuery) Listen for the click event on the captcha image. When the user clicks on the captcha image, a request will be triggered.
    • fetch('/api/captcha')or$.get('/api/captcha', ...)Send to the backend/api/captchaThe interface sends a request to get a new captcha image and its correspondingcaptcha_id.
    • After successfully obtaining the response, it will update the hidden field.captcha_idThe value, and update<img>label'ssrcProperty, display the new captcha image.
    • document.getElementById('get-captcha').click();or$('#get-captcha').click();Simulate a click after the page is loaded to ensure that the first captcha is displayed when the user sees the form.

After making these changes, save your template file. Now, when a user visits a page containing a message or comment form, they will see the captcha image, and they can refresh the captcha by clicking on the image.

Summary

By following these two simple steps, you can successfully enable and display the captcha feature in the Anq CMS message or comment form.This can not only effectively reduce the interference of garbage information, but also improve the security and user experience of the website.Ensure your website template files are modified correctly and fully tested after each update to ensure stable operation.


Frequently Asked Questions (FAQ)

  1. How do I solve the problem of not displaying or refreshing the captcha image?
    • Check background settings:Make sure you have checked and saved the 'Leave a message or comment and enable captcha' option in the 'Website Message' function of the Anqi CMS management background.
    • Check the network request:Open the browser developer tools (usually press F12), switch to the “Network” or “Network” tab. Try refreshing the page or clicking the captcha image, observe if there is a corresponding/api/captchaThe request. If the request fails (for example, the status code is not 200), please check your server logs for any relevant error messages, or check if your website has enabled firewall rules that may be blocking the request.
    • Check JavaScript error:Check for JavaScript error messages in the "Console" tab of the browser developer tools.This could be due to a syntax error in your frontend code or a conflict with other scripts.
  2. The captcha input is correct, but it prompts a captcha error when submitting the form?
    • Check field name:Please check the hidden fields you added in the templatecaptcha_idand the text input boxcaptchaofnameThe properties should be consistent with the code example. The backend will retrieve and verify the data based on these names.
    • Backend validation logic:Confirm that you have enabled the captcha function on the backend. If the backend is not enabled, even if the captcha is displayed on the frontend, the backend will not perform the check, which may lead to other errors.
    • The verification code has expired or is invalid:The captcha usually has a time limit, if the user stays on the form page for a long time without submitting, the captcha may have expired. It is recommended that the user try to refresh the captcha and submit again.
  3. Can this captcha mechanism be used in other forms on my website (such as contact forms, order forms)?
    • From a technical implementation perspective, the Anqi CMS provides/api/captchaThe interface is a general captcha generation and verification service. This means that as long as you copy and paste the same HTML structure and JavaScript code into the template of other forms, theoretically, you can enable the captcha in that form.But, be sure to confirm that the backend processing logic of this form has also integrated thecaptcha_idandcaptchaThe field validation is required, otherwise the captcha displayed on the front end is invalid.