You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AJAX删除问答回复失败问题排查及代码调试

问答页面AJAX删除回复功能故障排查

我基于AJAX开发了一个简易问答页面,发布问题、提交回复等功能均正常,但删除回复功能突然无法正常工作——该功能曾正常运行,我修改代码后又还原,但问题依旧。

持续收到以下错误:

SyntaxError: JSON.parse: unexpected end of data at line 41 column 1 of the JSON data

无论如何修改响应部分,问题都没有改善。

展示回复的页面代码

<?php
$stmt = $dbh->prepare("SELECT * FROM `replies` WHERE `title` = :title");
$stmt->bindParam(':title', $fetch2['title']);
$stmt->execute();
$replies = $stmt->fetchAll();

if (count($replies) == 0) {
echo '
  <center>
    <div class="col-lg-12" style="text-align:left;">
      <br><br>
      <small style="font-weight:bolder;padding:4px 12px;">No Replies Yet!</small><br><br>
      <hr style="background-color:#333;color:#333;height:1px;border:none;">
    </div>
  </center>
';
} else {

foreach ($replies as $reply) {

?>

<div class="" style="margin:0 auto;max-width:1280px;display:inline-flex;margin-bottom:12px;">
  <img src="/images/uploads/<?php echo $reply['img'];?>" style="width:42px;border-radius:50%;">
  <small style="margin-left:12px;"><b><?php echo $reply['username'];?></b></small>
</div>

<?php if ($userID == $reply['userID'] && $userdetails == $reply['username']): ?>

<div style="float:right;" class="dropdown">
  <iconify-icon role="button" aria-expanded="false" data-bs-toggle="dropdown" class="dropdown-toggle dropdown-toggle-custom" icon="gridicons:ellipsis" style="color:#888;float:right;"></iconify-icon>
  <style>
    /* Hide the default dropdown arrow for the custom class */
    .dropdown-toggle-custom::after {
      display: none;
    }
  </style>
  <ul class="dropdown-menu" style="background-color:#212529;color:#fff;">
    <li>
      <a style="color:black;" class="dropdown-item" href="#">Report Reply</a>
      <form id="delete-reply-form-<?php echo $reply['id']; ?>" action="/PHP/user_functions.php" method="POST">
        <input type="hidden" value="<?php echo $reply['id'];?>" name="id">
        <button class="dropdown-item deleteReply" name="deleteReply">Delete</button>
      </form>
    </li>
  </ul>
</div>

<?php else: ?>

<div style="float:right;" class="dropdown">
  <iconify-icon role="button" aria-expanded="false" data-bs-toggle="dropdown" class="dropdown-toggle dropdown-toggle-custom" icon="gridicons:ellipsis" style="color:#888;float:right;"></iconify-icon>
  <style>
    /* Hide the default dropdown arrow for the custom class */
    .dropdown-toggle-custom::after {
      display: none;
    }
  </style>
  <ul class="dropdown-menu" style="background-color:#212529;color:#fff;">
    <li>
      <a style="color:black;" class="dropdown-item" href="#">Report Reply</a>
    </li>
  </ul>
</div>

<?php endif; ?>

<br>

<div class="R" style="margin:0 auto;padding-left:6px;">
 <small style=""><?php echo $reply['reply'];?></small>
</div>

<small style="color:#666;float:right;">Replied: <?php echo date("d/m/Y" ,strtotime($reply['date']));?></small>

<hr style="background-color:#333;color:#333;height:1px;border:none;">

<?php
}}
?>

 <script>
 $(document).ready(function() {
 $(document).on("click", ".deleteReply", function(e) {
 e.preventDefault();

 var formData = {
 'id': $(this).closest('form').find('input[name="id"]').val()
 };

$.ajax({
type: "POST",
url: "/PHP/user_functions.php",
data: formData,
dataType: 'json',
success: function(response) {
console.log(response);
alert("Reply deleted successfully!");
$('#delete-reply-form-<?php echo $reply['id']; ?>')[0].reset();
},
error: function(xhr, status, error) {
console.log(error);
alert("An error occurred while deleting the reply.");
}
});
});
});
</script>

user_functions.php 修改记录

第一次修改后仍报错

SyntaxError: JSON.parse: unexpected end of data at line 47 column 1 of the JSON data

对应代码:

<?php
if (isset($_POST['deleteReply'])) {
$id = $_POST['id'];

$stmt = $dbh->prepare("DELETE FROM `replies` WHERE `id` = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();

// Prepare the JSON response
$response = array('success' => true, 'message' => 'Reply deleted successfully');

// Set the response header as JSON
header('Content-Type: application/json');
// Send the JSON response
echo json_encode($response);
exit();
}
?>

再次调整代码后收到对象错误

Object { success: false, message: "An error occurred while deleting the reply" }

调整后的前端JS代码:

$(document).ready(function() {
$(document).on("click", ".deleteReply", function(e) {
    e.preventDefault();

    var formData = {
        'id': $(this).closest('form').find('input[name="id"]').val()
    };

    console.log(formData);
    $.ajax({
        type: "POST",
        url: "/PHP/user_functions.php",
        data: formData,
        dataType: 'json'
    })
    .done(function(response) {
        console.log(response);
        if (response.success) {
            alert(response.message);
            $('#delete-reply-form-<?php echo $reply['id']; ?>')[0].reset();
        } else {
            alert(response.message);
        }
    })
    .fail(function(xhr, status, error) {
        console.log(xhr.responseText);
        alert("An error occurred while deleting the reply.");
    });
   });
 });

调整后的后端PHP代码:

<?php
if (isset($_POST['deleteReply'])) {
    $id = $_POST['id'];

    $stmt = $dbh->prepare("DELETE FROM `replies` WHERE `id` = :id");
    $stmt->bindParam(':id', $id);

    $success = $stmt->execute();

    if ($success && $stmt->rowCount() > 0) {
        // Reply was deleted successfully
        $response = array('success' => true, 'message' => 'Reply deleted successfully');
    } elseif ($success && $stmt->rowCount() === 0) {
        // No rows were affected
        $response = array('success' => false, 'message' => 'Reply deletion failed: No matching reply found');
    } else {
        // Reply deletion failed
        $response = array('success' => false, 'message' => 'Reply deletion failed');
    }

    // Set the response header as JSON
    header('Content-Type: application/json');
    // Send the JSON response
    echo json_encode($response);
    exit();
}

// If the code reaches here, an error occurred
$response = array('success' => false, 'message' => 'An error occurred while deleting the reply');
// Set the response header as JSON
header('Content-Type: application/json');
// Send the JSON response
echo json_encode($response);
exit();
?>

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 21:49:53