使用ajax时jQuery抓取错误的表单

时间:2015-01-27 22:23:47

标签: javascript php jquery

我有一个php函数,它循环通过数据库中的匹配,在循环内部,有一个表单返回到调用该函数的页面:

    while($row=mysql_fetch_array($get_unconfirmed))  
{ 
echo "<form name='confirm_appointment' method='post' class='confirm_appointment'>";
        echo "<input type='hidden' name='app_id' value='$appointment_id'>";
        echo "<input type='hidden' name='clinic_id' value='$clinic_id'>";
        echo "<td><input type='submit' class='update_appointment_button' value='$appointment_id'></td>";    
        echo "</form>"; 
}

然后我有jQuery提交表单:

$( document ).ready(function() {
    $(".update_appointment_button").click(function(){
        var url = "ajax/update_appointment_status.php";
        $.ajax({
               type: "POST",
               url: url,
               data: $(".confirm_appointment").serialize(), // serializes the form's elements.
               success: function(data)
               {
                   alert(data); // show response from the php script.
               }
             });
        return false; // avoid to execute the actual submit of the form.
    });
});

但问题是,它的设置方式,无论我推送“提交”的是什么行 - 我总是从最后一行(表单)中获取值。

所以我知道这个问题,我不是告诉jQuery从按下的按钮获取表单中的值。我需要以某种方式使用。这可能,但似乎无法找出正确的语法。

任何帮助都会被批评!

2 个答案:

答案 0 :(得分:2)

您可以像这样访问其父表单

data: $(this).closest(".confirm_appointment").serialize(),

或类似的东西

data: $this.parent().parent().serialize(), 

答案 1 :(得分:0)

另一种方法:使用click形式的事件替换按钮submit

$(document).ready(function () {

    $('.confirm_appointment').submit(function (e) {

        e.preventDefault();

        var url = "ajax/update_appointment_status.php";
        var serialized = $(this).serialize();

        $.ajax({
            type: "POST",
            url: url,
            data: serialized,
            success: function (data) {
                alert(data); // show response from the php script.
            }
        });
    });
});

JSFiddle demo