我得到每个按钮相同的价值

时间:2019-06-21 06:58:01

标签: javascript php ajax mysqli

我已经从数据库中获取数据,每件事都可以正常工作,但是问题是当我向test.php提交ajax请求时,我得到了每个按钮相同的值 我非常熟悉Ajax和Java,所以请帮助我,我混淆了如何分别获取每个按钮的价值并提交给test.php文件

/

这是我的test.php文件

<tbody>
    <?php
    $letter = mysqli_query($con,"SELECT * FROM letters order by id DESC");

    if (mysqli_num_rows($letter) > 0) {
        while ($rows_letter=mysqli_fetch_array($letter)) {
            $id = $rows_letter['id'];
            $subject = $rows_letter['subject'];
            $status = $rows_letter['status'];
            ?>

            <tr>
                <th class="text-center" scope="row">1</th>
                <td class="text-center"><?php echo $subject ;?></td>
                <td class="text-center">
                    <?php 
                    if ($status == 1) {
                        echo '<mark style="background-color: #5cb85c; color:white;"> Successfully Sent </mark>'; 
                    } else { 
                        echo '<mark  style="background-color:#f0ad4e; color:white;"> Not  Sent Yet </mark>';
                    }
                    ?>
                </td>
                <td>
                    <button type="button" class="btn btn-info btn-sm btn-block">
                    <span class="fa fa-pencil-square-o"></span> Edit</button>
                </td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm btn-block"> 
                    <span class="fa fa-trash-o"></span>  Move To Trash</button>
                </td>
                <td>
                    <button type="button" onclick="startsend();" id="id"  value="<?php echo $id;?>"class="btn btn-success btn-sm btn-block">
                    <span class="fa fa-paper-plane-o"></span> Send To All</button>
                </td>
            </tr>
            <?php
        }
    }       
    ?>
</tbody>
<script type='text/javascript'>

    //AJAX function
    function startsend() {
        var id = $('#id').val();
        $.ajax({
            type: "POST",
            url: "test.php",
            data:{ id: id
            },
            success: function(msg){
                alert( "Button Id is " + msg );
            }
        });
    }
</script>

1 个答案:

答案 0 :(得分:1)

尝试此操作,将ID作为param传递给ajax

HTML:

<td><button type="button" onclick="startsend(<?php echo $id;?>);"
      id="id"  value="<?php echo $id;?>"class="btn btn-success btn-sm btn-block">
      <span class="fa fa-paper-plane-o"></span> Send To All</button></td>

Ajax:

function startsend(id) {
      $.ajax({
        type: "POST",
        url: "test.php",
        data:{ id: id },
        success: function(msg){
          alert( "Button Id is " + msg );
        }
      });
    }