Javascript删除不起作用

时间:2015-10-14 13:41:52

标签: javascript php jquery mysql sql-delete

我的删除功能无效。

这是我的表格,带有删除按钮。

// retrieve table contents
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){

extract($row);

//creating new table row per record
echo "<tr>";
    echo "<td class='text-align-center'><input type='checkbox' name='item[]' class='checkboxes' value='{$employeeid}' /></td>";
    echo "<td>{$name}</td>";
    echo "<td>{$title}</td>";
    echo "<td>{$phone}</td>";
    echo "<td>{$supplier_name}</td>";
    echo "<td>{$created}</td>";
    echo "<td>";

        // update record
        echo "<a href='update_product.php?employeeid={$employeeid}' class='btn btn-info margin-right-1em'>";
            echo "<span class='glyphicon glyphicon-edit'></span> Rediger";
        echo "</a>";

        // delete record
        echo "<a delete-employeeid='{$employeeid}' delete-file='delete_product.php' class='btn btn-danger delete-object'>";
            echo "<span class='glyphicon glyphicon-remove'></span> Slet";
        echo "</a>";

    echo "</td>";
echo "</tr>";
}
//end table<br>
echo "</table>";

这是我的删除功能

// delete single record

$(document).on('click', '.delete-object', function(){


// php file used for deletion
var delete_file = $(this).attr('delete-file');

var id = $(this).attr('delete-id');
var q = confirm("Are you sure?");

if (q == true){

    $.post(delete_file, {
        object_id: id
    }, function(data){
        location.reload();
    }).fail(function() {
        alert('Unable to delete.');
    });

}
return false;
});

我从我修改过的教程中获得了很多代码。
除了删除功能外,其他所有功能都正常。

PHP代码

<?php
// check if value was posted
if($_POST){

    // include database and object file
    include_once 'config/database.php';

    // delete query
    $query = "DELETE FROM employeestest WHERE employeeid = ?";
    $stmt = $con->prepare($query);
    $stmt->bindParam(1, $_POST['object_employeeid']);

    if($stmt->execute()){
        // redirect to read records page and 
        // tell the user record was deleted
        echo "Medarbejderen er slettet.";
    }else{
        echo "Medarbejderen kunne ikke slettes.";
    }
}
?>

2 个答案:

答案 0 :(得分:0)

也许你只是犯了语法错误

'delete-id' => 'delete-employeeid'

答案 1 :(得分:0)

更改

var id = $(this).attr('delete-Id');

var id = $(this).attr('delete-employeeid');

并且,将$.post更改为$.ajax,因为我已经

<script>
    $(document).on('click', '.delete-object', function(){
        var delete_file = $(this).attr('delete-file');
        var id = $(this).attr('delete-employeeid');
        var q = confirm("Are you sure?");
        if (q == true)
        {
            $.ajax({url:delete-file,cache:false,success:function(result){
                alert('Successfully Deleted');
            }});
        }
        return false;
    });
</script>