How to integrate the AnQiCMS built-in captcha feature into the comment form to prevent spam?

Calendar 👁️ 84

As website operators, we often encounter a headache-inducing problem: spam information.Whether it is a message board or a comment section, advertisements that come uninvited, malicious links, and meaningless content not only harm the image of the website and increase the management burden, but may also affect the SEO performance of the website.It's good that AnQi CMS considered these security requirements from the beginning, built-in captcha functions, helping us easily cope with these challenges.

Today, let's talk about how to integrate this powerful captcha function into the留言or评论form of your Anqi CMS website, keeping your site fresh and secure.

Enable captcha function with one click in the background

The first step in integrating the captcha function is naturally to make a simple configuration in the Anqi CMS background. The entire process is very intuitive and does not require complex settings.

You just need to log in to your Anqi CMS backend, find the menu on the left“Function Management”. Here, you can choose to enter as needed“Website Message Management”or“Content Comment Management”. After entering the corresponding management interface, you will see a name called“Turn on the comment/review captcha function”The option. Typically, this is just a simple toggle switch, click to set it to the 'on' state.

After completing this step, the Anqi CMS backend is ready to provide captcha services for your form.Next, we will add the display and interaction logic of the captcha in the front-end template.

Front-end template integrated captcha code

After enabling the background function, we need to modify the front-end message or comment form template file, embedding the display element and interactive script of the captcha.The AnQi CMS template system is flexible and easy to use, even for beginners who can quickly get the hang of it.

We need to add several key elements to the form: one for displaying the captcha image<img>label, one for the user to enter the captcha<input type="text">Label, as well as a hidden field for backend validation<input type="hidden">.

You can place the following code snippet in your message or comment form (usuallyguestbook/index.htmlor in the template file related to comments) of<form>Label inside, ensure they are submitted with the form:

<div style="display: flex; clear: both">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" class="layui-input" style="flex: 1">
  <img src="" id="get-captcha" style="width: 150px;height: 56px;cursor: pointer;" alt="验证码" />
  <script>
    // 原生JavaScript方式获取验证码
    document.getElementById('get-captcha').addEventListener("click", function (e) {
      fetch('/api/captcha') // 向安企CMS内置的API接口请求验证码数据
              .then(response => {
                return response.json()
              })
              .then(res => {
                // 将后端返回的验证码ID赋值给隐藏字段
                document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
                // 将后端返回的验证码图片URL赋值给img标签的src属性
                document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
              }).catch(err => {
                  console.error('获取验证码失败:', err);
              })
    });
    // 页面加载时自动触发一次点击,显示初始验证码
    document.getElementById('get-captcha').click();
  </script>
</div>

If your website template uses the jQuery library, you can also use the following more concise JavaScript code:

<div style="display: flex; clear: both">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" class="layui-input" style="flex: 1">
  <img src="" id="get-captcha" style="width: 150px;height: 56px;cursor: pointer;" alt="验证码" />
  <script>
    // jQuery方式获取验证码
    $('#get-captcha').on("click", function () {
      $.get('/api/captcha', function(res) {
        $('#captcha_id').attr("value", 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>
</div>

The core logic of this code is:

  1. When the page is first loaded, JavaScript will send throughfetch(or$.get)to the built-in of AnQi CMS/api/captchainterface request.
  2. The interface will return a containingcaptcha_id(Unique identifier for the verification code) andcaptchaThe JSON data of the captcha image's Base64 encoding or URL.
  3. JavaScript will fill it after receiving the data.captcha_idinto the hidden&lt;input type="hidden"&gt;field, and at the same timecaptchaThe image is displayed in&lt;img&gt;the tag.
  4. If the user finds the captcha not clear, they can click the image, JavaScript will request a new captcha again, realizing the refresh function.
  5. When the user submits the form,captcha_idand the input of the usercaptchathe value will be sent to the backend for verification.

Test and verify

After completing the code integration, be sure to perform detailed testing. You can:

  • Visit your website's message or comment page and check if the captcha image is displayed normally.
  • Try clicking on the captcha image to see if a new captcha will refresh.
  • Try entering an incorrect captcha and submit to see if the system can intercept it correctly.
  • Enter the correct captcha to submit, ensure that the message or comment can be published normally.

By following these simple steps, you have effectively provided a strong security shield for the留言or评论function of your Anqi CMS website, effectively resisting the interference of spam information, making your website content environment cleaner and more controllable.


Frequently Asked Questions (FAQ)

1. How do I handle the situation where the captcha image does not display or refresh fails?

First, make sure you have enabled the corresponding captcha function in the "Function Management" -> "Website Message Management" or "Content Comment Management" of the Anqi CMS backend. If the backend is enabled, please check the console for JavaScript errors in your browser's developer tools (usually open by pressing F12), as well as in the Network tab for/api/captchaIs the interface request successful (return status code 200)? Common errors may include incorrect interface address spelling, network connection issues, or incorrect server response.

Can I customize the captcha style?

Of course you can. The captcha image is usually generated by the Anqi CMS backend, but its external container (such as in our example,&lt;div&gt;and&lt;img&gt;The style of the label is completely controlled by your frontend CSS. You can modify the example code in&lt;div&gt;and&lt;img&gt;On the tagstyleproperties, or add custom ones to themclassThen write the corresponding style rules in your CSS file to match the overall design style of your website.

3. Can this captcha feature only be used for message forms? Can I use it on other custom forms?

The AnQi CMS built-in captcha feature is designed to be universal, applicable not only to message and comment forms, but theoretically also to any custom form that requires user input and prevents spam. As long as you can obtain the form's HTML template, and follow the HTML structure and JavaScript logic introduced in our article, correctly embed the captcha element and request script into your custom form, and ensure that the form submission will includecaptcha_idandcaptchaThe field is sent to the backend for verification and can be implemented. The specific implementation may require a deeper understanding of the Anqicms backend validation logic, or writing custom backend handling logic for your form to call the captcha module.

Related articles

How does AnQiCMS implement the dynamic display of breadcrumb navigation through template tags?

In web design, breadcrumb navigation is a seemingly minor but actually crucial feature.It clearly shows the user's current position in the website in a concise path form, not only effectively improves user experience and helps visitors quickly understand the website structure and easily backtrack, but also greatly benefits search engine optimization (SEO), as it can provide clear website hierarchy information for search engine crawlers and enhance the internal link structure of the website.

2025-11-08

How can I ensure that the front-end display content is synchronized after batch replacing keywords in content management?

In website content operation, sometimes we need to perform unified keyword adjustments on a large amount of on-site content, whether it is for SEO optimization, brand word unification, or to cope with changes in content strategy, AnQiCMS (AnQiCMS) provides a convenient batch replacement function.However, after completing the replacement operation, how can we ensure that the front-end users can see these updates immediately when they visit, which is a concern for many operators.

2025-11-08

How to extract the specified length of the article title or description in AnQiCMS template and add an ellipsis?

In AnQiCMS template development, we often need to control the length of article titles or descriptions to maintain a tidy and unified visual effect on list pages, card layouts, or other compact display areas.At the same time, it is customary to add an ellipsis when the content is truncated, which can kindly prompt readers that there is more content here.AnQiCMS's powerful template engine is built-in with a rich set of filters (Filters), making this task extremely simple and efficient.### Understanding the need for content truncation Whether it's an article list, recommendation position, or SEO meta description

2025-11-08

How to filter and display content in AnQiCMS template based on the article's 'recommended attributes' (such as headline, slideshow)?

In website content operation, displaying carefully selected high-quality content in an eye-catching manner to users is a key factor in improving user experience, guiding reading behavior, and achieving operational goals.AnQiCMS (AnQiCMS) fully understands this and provides a flexible and powerful "recommended attribute" function to make content filtering and display simple and efficient.By setting different recommendation attributes for articles, we can accurately present specified types of content in various areas of the website, whether it's the headline news on the homepage or the stunning images in the carousel, it can be easily achieved.###

2025-11-08

How to display all articles under a specific Tag in AnQiCMS?

In AnQiCMS, displaying the list of all articles under a specific tag (Tag) is a common and practical content operation requirement.Through AnQiCMS's flexible template system, you can easily implement this feature, providing users with more accurate content navigation.Let's first understand the tag mechanism in AnQiCMS.Tags are important tools for content organization, allowing you to add keywords to articles, products, and other content to cross-reference related items, even if they belong to different categories.This association method helps users discover more interesting content

2025-11-08

How to insert preset content from the paragraph material library in the article content editor?

In AnQi CMS, efficiently managing and publishing content is the key to improving operational efficiency.For scenarios where frequent use of specific statements, module introductions, or standard declarations is required, manual repetition not only takes time but may also introduce inconsistencies.AnQi CMS understands the value and challenges of content creation, and therefore cleverly integrated the "Paragraph Material Library" feature into the article content editor, aiming to help you easily solve this pain point.Today, let's delve into how to easily insert predefined content from the paragraph material library in the article content editor, to increase your content production efficiency

2025-11-08

How to call and display the friend link list in AnQiCMS templates?

How to effectively call and display the friend link list in the template when building and managing a website using AnQiCMS is a common and practical need.Friendship links can not only help improve the SEO performance of the website, but also provide users with more valuable external resources.The powerful template engine of AnQiCMS combined with its backend features makes this operation very direct.### Manage友情链接: Start from the backend Before displaying the友情链接 on the website frontend, we first need to set it up in the AnQiCMS backend

2025-11-08

How to dynamically display the publication time of an article and format it on the article detail page?

Managing content in AnQi CMS, the publication time is undoubtedly an indispensable important metadata for every article.It not only allows readers to understand the timeliness of the content, but also has a positive impact on the website's SEO.The AnQi CMS provides us with a very convenient and flexible way to dynamically display and format these publishing times on the article detail page. <h3>Get the publication time of the article On the Anqi CMS article detail page, the system will automatically provide us with all the information of the current article as context variables.Among them, the publication time of the article is stored in

2025-11-08