How to enable and display the captcha function correctly in the website's comment and message form?

Calendar 81

When running a website, spam comments and malicious messages often cause headaches.They not only affect user experience, but may also consume server resources, even lowering the professional image of the website. 幸运的是,AnQi CMS 内置了验证码功能,可以帮助我们有效地过滤这些不期而至的客人,使网站环境更加清新。

Below, we will together learn how to enable and correctly display the captcha function in the website's comment and message form.

Step 1: Enable captcha functionality in the background

Firstly, we need to go to the management interface of the website backend. Find "Function Management" in the left navigation bar and then choose to enter "Website Message Management" or "Content Comment Management" according to your needs.These modules usually have a similar configuration item.

After entering the corresponding management page, you will see an option named "Whether to enable captcha" or something similar. Check it to enable and save the settings.

This step is crucial, it informs the Anqi CMS backend system that a captcha check needs to be performed when handling comment or message submissions.If the backend is not enabled, even if the code to display the captcha on the front end is added, the captcha will not work normally because the backend will not verify it.

Step 2: Modify the website template file to display the captcha

Next, we need to modify the website's front-end template file so that the user can see and enter the captcha when submitting the form. Usually, the message form is located in your template directory.guestbook/index.htmlIn the document, while the comment form may be in the template of the article or product details page (such asarchive/detail.htmlorproduct/detail.html) or a dedicated comment list template (comment/list.html).

Find the form you want to add the captcha to and add the following HTML and JavaScript code near the submit button.This code mainly includes three parts: a hidden input box for storing the captcha ID, a text input box for users to enter the captcha, and an image tag for displaying the captcha image.

<div style="display: flex; clear: both; align-items: center; margin-bottom: 15px;">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" style="flex: 1; padding: 10px; border: 1px solid #ccc; margin-right: 10px; border-radius: 4px;">
  <img src="" id="get-captcha" style="width: 150px; height: 40px; cursor: pointer; border: 1px solid #eee; border-radius: 4px;" alt="验证码">
</div>

<script>
  // 获取验证码的函数
  function fetchCaptcha() {
    fetch('/api/captcha')
      .then(response => response.json())
      .then(res => {
        if (res.code === 0 && res.data) {
          document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
          document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
        } else {
          console.error('获取验证码失败:', res.msg);
        }
      })
      .catch(err => {
        console.error('请求验证码接口出错:', err);
      });
  }

  // 页面加载完成后立即获取一次验证码
  document.addEventListener('DOMContentLoaded', function() {
    fetchCaptcha();
  });

  // 点击验证码图片时刷新验证码
  document.getElementById('get-captcha').addEventListener("click", function () {
    fetchCaptcha();
  });
</script>

If you use the jQuery library on your website, you can also use the following more concise jQuery syntax:

<div style="display: flex; clear: both; align-items: center; margin-bottom: 15px;">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" style="flex: 1; padding: 10px; border: 1px solid #ccc; margin-right: 10px; border-radius: 4px;">
  <img src="" id="get-captcha" style="width: 150px; height: 40px; cursor: pointer; border: 1px solid #eee; border-radius: 4px;" alt="验证码">
</div>

<script>
  // jQuery 调用方式
  function fetchCaptchaWithJquery() {
    $.get('/api/captcha', function(res) {
      if (res.code === 0 && res.data) {
        $('#captcha_id').attr("value", res.data.captcha_id);
        $('#get-captcha').attr("src", res.data.captcha);
      } else {
        console.error('获取验证码失败:', res.msg);
      }
    }, 'json').fail(function(jqXHR, textStatus, errorThrown) {
      console.error('请求验证码接口出错:', textStatus, errorThrown);
    });
  }

  $(document).ready(function() {
    fetchCaptchaWithJquery(); // 页面加载后获取验证码
    $('#get-captcha').on("click", function () {
      fetchCaptchaWithJquery(); // 点击图片刷新验证码
    });
  });
</script>

This JavaScript code is responsible for sending to the/api/captchaThe interface initiates a request to obtain a new captcha image and the corresponding ID. Then, it will display the obtained captcha image in<img>the tag and fill the captcha ID into the hiddencaptcha_idWithin the input box. After the user enters the captcha, the system will use this ID to verify whether the input is correct.In order to make the captcha image and input box look more coordinated, some basic CSS styles have already been provided in the above example. You can adjust and beautify them according to the overall style of the website.

Place the above code snippet correctly in your comment or message<form>Inside the tag and make surecaptcha_id/captchaandget-captchaThe IDs of these elements are unique in your template to avoid conflicts.

By following these two simple steps, your Safe CMS website can effectively enable captcha functionality in comment and message forms.This can significantly reduce the disturbance of spam information, protect the purity of the website content, and improve the overall operational efficiency.Good user experience and website security are parallel, and CAPTCHA is an effective tool to balance both.


Frequently Asked Questions (FAQ)

1. Ask: Why does the captcha image not display even though I followed the steps?

Answer: This may be caused by several reasons. First, please confirm again whether you have checked and saved the option 'Whether to enable captcha' under 'Function Management' in the Anqi CMS backend for 'Website Message Management' or 'Content Comment Management'.Next, check the browser console (usually opened by pressing F12) for any failed network requests (404 or 500 errors) or JavaScript errors.Confirm your website can be accessed/api/captchaAccess the captcha interface path, and the data format it returns is correct. Finally, also check if the CSS style you added has accidentally hidden the captcha image.

2. Ask: I have enabled the captcha, but there are still spam comments submitted, what is the matter?

Answer: CAPTCHA can effectively filter out most automated, low-level forms of spam robots.However, for some more advanced robots, or spam comments released through manual operation, the captcha may not completely prevent.In this case, you can consider combining other content security features of Anqi CMS, such as sensitive word filtering, manual review mechanisms, or setting comment submission frequency limits to further enhance the preventive effect.

3. Ask: Can I change the display style of the captcha or replace it with another type?

Answer: The captcha function built into Anqi CMS usually provides a default image.

Related articles

How to display友情链接 in front-end and add nofollow attribute according to needs?

Manage and display friend links in Anqi CMS, which not only helps to enrich the external connections of the website, but also is a delicate operation that needs to be fine-tuned during SEO optimization.It is particularly important to flexibly control the `nofollow` attribute according to requirements, which is crucial for maintaining the health of website links and the transmission of weight.Our Aiqi CMS provides intuitive and powerful features, allowing us to easily achieve these goals.--- ### Configure friend links in AnQi CMS backend Firstly, all the friend links displayed on the front end cannot be separated from the detailed configuration in the backend

2025-11-08

How does AnQiCMS automatically generate Sitemap and configure Robots.txt to optimize search engines' crawling and display of website content?

Search engine optimization (SEO) is the cornerstone of any website's success, and Sitemap and Robots.txt files are the key tools we use to communicate with search engines.They are like the 'instruction manual' and 'traffic rules' of a website, helping search engines efficiently and accurately crawl and display our content. 幸运的是,AnQiCMS was well thought out from the beginning of its design, built-in powerful SEO tools, making these seemingly complex operations extremely simple. Next

2025-11-08

How to customize the website navigation menu and control its display order and level relationship at different positions on the website?

The website navigation is a map for users to browse the website, not only guiding users to find the information they need, but also reflecting the structure of the website and the user experience.In AnQi CMS, customizing and managing the navigation menu of a website, including their display order and hierarchical relationships, is an operation that is flexible and efficient.In order to optimize the user experience, or to better support content marketing and SEO strategies, Anqi CMS provides powerful and intuitive tools.Next, we will explore how to customize your website navigation in Anqi CMS in detail.

2025-11-08

How to set and display the global contact information (phone, address, email, social media, etc.) of AnQiCMS?

In website operation, clear and convenient contact information is the key to building trust and promoting communication.Whether it is a phone number, address, email, or increasingly important social media channels, this information needs to be prominently and consistently displayed on your website.AnQiCMS knows this, therefore it provides a直观且集中的 way to manage the global contact information of the website, allowing your visitors to easily find you wherever and whenever.

2025-11-08

How to overview the key operational data display of the AnQiCMS backend homepage (such as document quantity, visit trend, inclusion situation)?

The AnQi CMS backend homepage: A smart overview of website operations In the ever-changing internet environment, an efficient and intuitive website operation backend is undoubtedly the key to controlling the overall situation for operators.AnQiCMS (AnQiCMS) fully understands this, and the design philosophy of its backend homepage is to present the core operational data of the website in a clear and easy-to-understand way in front of you, so that you can have a clear understanding of the health status and operational performance of the website at the first time.

2025-11-08

How does AnQiCMS handle the conversion of uploaded image webp format, large image compression, and thumbnail generation to optimize display performance?

In this era of pursuing speed and visual experience, the loading efficiency of website images is directly related to user retention and search engine rankings.We all hope that the images on the website can be presented in high definition and quickly displayed to the user.AnQiCMS provides us with a very practical solution in image processing, through functions such as WebP format conversion, intelligent large image compression, and diverse thumbnail generation, which help us easily optimize website images and make the website run more smoothly.### WebP Format Conversion: The Balance of Lightweight and High Definition WebP

2025-11-08

How to set and accurately display the TDK (Title, Description, Keywords) on the homepage of AnQiCMS?

The homepage, just like the digital facade of your company or brand.It is not only the first impression of your visitors, but also the key to search engines evaluating the core value of your website.The TDK - Title, Description, and Keywords on the homepage play a crucial role in Search Engine Optimization (SEO).A well-set homepage TDK can effectively improve the ranking of the website in search results, attract more target users to click, and bring considerable traffic and conversion.

2025-11-08

How to use the `include` tag in AnQiCMS templates, efficiently reuse and display common page header, footer and other modules?

When building a website, we often encounter such a scenario: the website header (Header), footer (Footer), sidebar (Sidebar), and navigation menu modules, almost appear on every page.These modules are not only similar in content, but also their structure and style need to be maintained consistently.If you write the same code for each page, it is not only inefficient, but also a maintenance nightmare if you need to make any changes, as you would have to adjust all pages one by one.Luckyly, AnQiCMS (AnQiCMS) understands the importance of template reuse

2025-11-08