I have the script below that erases a line on a MySQL database with ajax. When the function is fired the line gets deleted from the database but I am always alerted "FAILED".
function deleteRow(data){
if(confirm("Are you sure that you wish to remove this entry?
This 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");
});
}
}
This is 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();
}
Change the PHP and return 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);
?>
and
.done(function(data) {
if (data.success == 'true') {
alert('you did it');
}
})