jQuery AJAX删除只捕获第一个表单

时间:2017-07-31 07:11:05

标签: javascript php jquery ajax

我试图对一个删除数据库中的行的php文件进行AJAX调用,现在问题是它只删除了第一行...我已经研究了这个似乎没什么用,所以我决定来这里寻求帮助! (gif更好地解释一下我是控制台。记录jQuery https://thumb.gyazo.com/thumb/1200/_9f12c592fc900ae5fa7b1247257119fd-gif.gif选择的ID) 这是代码:
jQuery AJAX

    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $(".notif_delete").click(function(event){




    // setup some local variables
    var $form = $(this).closest("form");

    // Serialize the data in the form
       var Data = {

                'notif_id': $('input[name="notif_id"]').val()

            };
    // Fire off the request to php file
    request = $.ajax({
        url: "#notification_control.php",
        type: "post",
        data: Data
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked delete!");
        console.log($('input[name="notif_id"]').val());


    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.log("The following error occurred deleting:" + errorThrown);
                console.log($('input[name=notif_id]').val());
    });
    });

PHP

if(isset($_POST['notif_id'])) {
$stmt = $conn->prepare("DELETE FROM notifications WHERE notif_id = ?");
$stmt->bind_param("i", $_POST['notif_id']);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
}

HTML

<form method="POST">
<a <?php echo ($isread == 'no') ? 'class="notification unread"' : 'class="notification"'; ?>><?=  '<img src="../profile_pictures/' . $picture . '">' . '<b>'. $from . '</b><br>' . '<span class="notification-text">' . $text . '</span>' . '<span class="notif_delete glyphicon glyphicon-remove" aria-hidden="true"></span>'?></a>
<input type="hidden" name="user_id" value="<?=$_SESSION['id']?>">
<input type="hidden" name="notif_id" value="<?=$notif_id?>"> </form>

1 个答案:

答案 0 :(得分:0)

正如我想的那样根据你的gif -

您有多个具有相同名称的隐藏字段,即notify_id

所以每当你选择'notif_id'时:$('input [name =“notif_id”]')。val() 它显然会选择第一行。

我认为这是你面临的唯一问题。

just 2 steps - 
1st> in the anchor tag add custom attribute  notifyId="<?=$notif_id?>"
2nd> replace $('input[name="notif_id"]').val() with $(this).attr('notifyId')

这就是全部。