You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PHP中input标签内onClick事件失效:ajax_post函数未执行问题

Fixing the Uncalled ajax_post() Function on Button Click

Let's break down why your button isn't triggering the ajax_post() function, and how to fix it quickly.

The Core Issue: Incorrect onClick Syntax

Your current echo statement wraps the function call inside a <script> tag within the onClick attribute—this is invalid. The onClick event handler expects raw JavaScript code directly, not a full script tag.

Your Original Code:

echo "<input type=\"button\" id=\"csubmit\" value=\"SUBMIT\" onClick=\"<script type='text/javascript'>ajax_post();</script>\">";

Corrected Code:

Remove the <script> tags from the onClick attribute, and just call the function directly:

echo "<input type=\"button\" id=\"csubmit\" value=\"SUBMIT\" onClick=\"ajax_post();\">";
// Or even cleaner, use single quotes to avoid escaping double quotes:
echo '<input type="button" id="csubmit" value="SUBMIT" onClick="ajax_post();">';

Additional Checks to Ensure Everything Works

Even after fixing the syntax, there are a few more things to verify:

  • Make sure ajax_post() is loaded before the button: The function in comments.php needs to be included in the page before this button renders. If the button loads first, the browser won't recognize the function when the click happens.
  • Check browser console for errors: Open your browser's dev tools (F12) and go to the Console tab. Look for errors like "ajax_post is not defined"—this will tell you if the function isn't being loaded properly.
  • Validate your AJAX logic: Double-check the ajax_post() function to ensure:
    • The XMLHttpRequest object is created correctly (add fallback for older IE versions if needed)
    • The request URL and method are correct
    • You're handling the response properly
  • Test the database insertion separately: To rule out AJAX issues, try calling the database logic directly (without AJAX) to confirm it works as expected.

By fixing the onClick syntax first, then verifying these other points, your button should trigger the function and execute the database insertion as intended.

内容的提问来源于stack exchange,提问作者SATYAM SAREEN

火山引擎 最新活动