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 annoyance of spam and malicious flooding.In order to effectively filter out this unnecessary content, enabling the captcha mechanism has become a simple and efficient solution.Auto CMS (AnQiCMS) provides us with a flexible way to easily integrate captcha functionality into comment or review forms.

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

Step 1: Enable the captcha feature in the admin backend.

Firstly, 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. Login to your Anqi CMS management background.
  2. Find "Function Management" in the left navigation menu and then click "Website Messages".
  3. On the website message management interface, you will see an option named "Is the captcha enabled for messages or comments".Please make sure this option is checked or set to 'On' status, and save your settings.

This operation informs the system that captcha verification is required when users submit messages or comments.

第二步:Modify the front-end template, integrate captcha display

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

The template files of Anqi CMS are usually located in/templateUnder the directory, specific to the message or comment form, you may need to find similarguestbook/index.htmlorcomment/list.htmlSuch a file, the specific filename may vary depending on the template you are using. Find the location of the form (usually starting with a label), and add the following code snippet.<form>(usually starting with a label) located position, and add the following code snippet.

Example HTML structure and JavaScript code

To make the captcha image dynamic and include the correct captcha identifier when submitted, you can add the following HTML structure at an appropriate location 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>

Using jQuery in a simplified way

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 each time the captcha is created.This ID is sent to the backend along with the form submission by the user, used to match whether the entered captcha is correct.
  • <input type="text" name="captcha" required placeholder="请填写验证码" ...>: This is the text box for user input of the verification code.
  • <img src="" id="get-captcha" alt="验证码" ...>This is the position where the verification code image is displayed. We dynamically set it through JavaScript.srcproperties.
  • JavaScript code block:
    • It first goes throughdocument.getElementById('get-captcha').addEventListener("click", ...)(Pure JavaScript) Or$('#get-captcha').on("click", ...)(jQuery) Listen for the click event on the captcha image. When the user clicks the captcha image, a request will be triggered.
    • fetch('/api/captcha')or$.get('/api/captcha', ...)To the backend/api/captchaInterface sends request to get a new verification code image and its correspondingcaptcha_id.
    • After successfully obtaining the response, it will update the hidden fieldcaptcha_idvalue, and update<img>Tagssrcthe property to display the new verification code image.
    • document.getElementById('get-captcha').click();or$('#get-captcha').click();Simulate a click after the page loads to ensure that the first captcha is displayed as soon as the user sees the form.

Complete these modifications and save your template file.Now, when users visit a page that includes a message or comment form, they will see the captcha image and can refresh the captcha by clicking on the image.

Summary

By following these two simple steps, you can successfully enable and display the captcha function in the留言 or 评论 form of the 安企CMS.This can not only effectively reduce the interference of garbage information, but also improve the security and user experience of the website.Ensure that your website template file is modified correctly and that it is thoroughly tested after each update to ensure stable operation of the functionality.


Common Questions (FAQ)

  1. What if the captcha image does not display or cannot be refreshed?
    • Check background settings:Ensure that you have checked and saved the '留言或评论是否开启验证码' option in the 'Website Messages' feature of the Anqi CMS management backend.
    • Check the network request:Open the browser developer tools (usually by pressing F12), switch to the "Network" or "Network" tab. Try refreshing the page or clicking on the captcha image, observe if there is a corresponding response/api/captchaThe request.If the request fails (for example, the status code is not 200), please check your server logs to see if there are any related error messages, or check if your website has firewall rules enabled that may be blocking the request.
    • Check JavaScript error:Check for JavaScript error messages in the 'Console' tab or 'Console' section of the browser's developer tools.This may be due to syntax errors in your front-end code or conflicts with other scripts.
  2. Captcha entered correctly, but received a captcha error when submitting the form?
    • Field name check:Please carefully check the hidden fields you have added in the template.captcha_idAnd the text input boxcaptchaofnameWhether the properties are exactly 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 validation, which may lead to other errors.
    • Code expired or 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 refresh the captcha and submit again.
  3. Can this verification code mechanism be used in other forms on my website (e.g., contact form, order form)?
    • From the perspective of technical implementation, the CMS provided by Anqi/api/captchaThe interface is a general-purpose captcha generation and verification service.This means that, theoretically, you can enable the captcha in the form by copying and pasting the above same HTML structure and JavaScript code into the template of another form.captcha_idandcaptchaField validation, otherwise the verification code displayed on the front end is invalid.