How to enable and display captcha in the comment or message form?

Calendar 👁️ 75

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.

Related articles

How to add structured data (JSON-LD) in the HTML header to improve search result display?

In today's highly competitive online environment, it is crucial to make your website content stand out in search engine results pages.In addition to high-quality content and an excellent keyword strategy, structured data (especially in JSON-LD format) plays an increasingly important role.It can help search engines understand the information on your page more accurately, so that your content may be displayed in richer, more attractive forms in search results (such as rich media summaries, i.e., Rich Snippets).What is JSON-LD and why should it be used

2025-11-08

How to deploy multiple AnQiCMS sites on the same server and ensure their independent display?

Deploying multiple websites on the same server while ensuring that they run and display independently is a common need for many content operators.For AnQiCMS users, this is not only feasible but also very efficient.The Anqi CMS leverages its powerful multi-site management features, allowing you to easily manage multiple brand sites, sub-sites, or content branches with just one core program.Next, we will discuss in detail how to deploy and manage multiple security CMS sites cleverly on the same server, so that they operate independently without interfering with each other.### Core Concept

2025-11-08

How to display the current year or other system time information in the template?

In website operation, keeping your content up-to-date in real-time, especially information like the year or date of system time, can not only enhance the professionalism of the website but also provide users with more accurate references.AnQiCMS as a flexible and efficient content management system provides a variety of convenient ways for you to easily implement this requirement. Next, let's learn how to flexibly display the current year or other system time information in the AnQiCMS template.### Display the current system time——`{% now %}`

2025-11-08

How does the automatic compression of images and the handling of large images in content settings affect page display performance?

In website operation, images are indispensable elements that enrich content and attract users.However, if image processing is not handled properly, the large file size often becomes the culprit that slows down page loading speed, thereby affecting user experience and search engine optimization (SEO) performance.AnQiCMS provides a series of powerful image processing features in its content settings, aimed at helping us easily optimize images and significantly improve the display performance of the website.When a visitor opens a page, the browser needs to download all the resources on the page, including text, styles, scripts, and images.If the image file is too large

2025-11-08

How can language switch links be displayed in multilingual sites?

Build a website for global users, multilingual support is an indispensable part.AnQiCMS was designed with this in mind, providing a powerful and flexible solution for the publication and management of multilingual content.By making some simple configuration and template adjustments, we can easily implement language switching functionality on the website, allowing users of different languages to smoothly browse the website content.### AnQiCMS' multilingual capabilities AnQiCMS is inherently equipped with excellent multilingual content management capabilities

2025-11-08

How to display a user or user group in the template

In AnQi CMS template design, it is crucial to be able to flexibly display user or user group information, which is essential for building personalized, interactive website experiences.AnQi CMS provides intuitive and powerful template tags, allowing you to easily display rich information such as users' profiles and user groups on the front end of the website, thereby enhancing user engagement and the professionalism of the website.Whether you want to display the user's nickname and membership level in the article comment area or show specific content and features based on the user's identity or group, Anqi CMS provides the `userDetail` and

2025-11-08

How can you accurately convert a numeric string to a floating-point number in the Anqi CMS template?

In AnQi CMS template development, we often need to handle various types of data, where the conversion between numeric strings and floating-point numbers is a common and important requirement.For example, you may get a custom field from the background, such as a price (like "12.50"), or a numeric product inventory (like "100"), when performing mathematical operations, comparing sizes, or displaying in a specific format in the template, it is particularly important to convert it from a string type to a floating-point number accurately

2025-11-08

What value will the `float` filter return when encountering a non-numeric string?

In AnQi CMS template development, filters are an important tool for processing and formatting data.They can help us present the data passed from the backend in a way that is more in line with the front-end display requirements.Among them, the `float` filter is specifically used to convert numbers to floating-point format.However, when it encounters a non-numeric string, its behavior becomes particularly critical because it directly affects the accuracy of the template output and the stability of the program.The core function of the `float` filter is to convert the input value to a floating-point number type

2025-11-08