jQuery ajax总是在Wordpress上失败

时间:2014-01-08 22:06:29

标签: 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();
}

1 个答案:

答案 0 :(得分:5)

更改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');
     }
})