javascript - jQuery ajax 完成在 WordPress 上总是失败

标签 javascript php jquery ajax wordpress

我有下面的脚本,它使用 ajax 删除 MySQL 数据库上的一行。当该函数被触发时,该行将从数据库中删除,但我总是收到“失败”警报。

function deleteRow(data){
if(confirm("Are you sure that you wish to remove this entry?\nThis cannot be undone")){
    $.ajax({
            type: "POST",
            url: "/wp-content/themes/Rexmed/deleterow.php",
            data: {id: data},
            dataType: "json"
        }).done(function() {
            alert("Success");
        }).fail(function() {
            alert("FAILED");
        });
}
}

这是deleterow.php

<?php
require('../../../wp-blog-header.php');
if(!is_user_logged_in()){
auth_redirect();
die();
}

require ('../../../wp-config.php');
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$id = $_POST['id'];

if ($stmt = $mysqli->prepare("DELETE FROM customers WHERE id=?")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->close();
}

最佳答案

更改 PHP 并返回 JSON

<?php
    require('../../../wp-blog-header.php');
    if(!is_user_logged_in()){
        auth_redirect();
        die();
    }

    require ('../../../wp-config.php');
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    $id = $_POST['id'];

    if ($stmt = $mysqli->prepare("DELETE FROM customers WHERE id=?")) {
        $stmt->bind_param("s", $id);
        if ($stmt->execute()) {
            $arr = array('success' => 'true');
        }else{
            $arr = array('success' => 'false');
        }
        $stmt->close();
    }

    echo json_encode($arr);

?>

.done(function(data) {
     if (data.success == 'true') {
        alert('you did it');
     }
})

关于javascript - jQuery ajax 完成在 WordPress 上总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21007589/

相关文章:

javascript - 从变量对象中删除 DOM 元素以将其发布到服务器

javascript - 优化 if else 条件 javaScript

javascript - 如果其他打开,jQuery 关闭 ul

php - shell heredoc inside php heredoc

php - 如何在 mysql + codeigniter 中按开始时间/结束时间过滤记录

javascript - 使用 hide、prop、attr 或 css 与 JQuery 隐藏元素之间的区别

javascript - 如何即时向 jQuery slider 添加多个句柄

java - 将 tinyMCE 与 Jspell 集成以进行拼写检查?

javascript - 如果内值为负数,则更改 HTMLDIVS 中的所有值

javascript - 我如何让 Google Analytics 跟踪幻灯片中的单个图像?