doswy02440 2016-10-19 22:28
浏览 71
已采纳

PHP多选 - 使用ajax发送选项数据[重复]

I want to change the status in the database, with a select dropdown field. I am sending with ajax. The first row is always working, but with multiple data i cant update the second, third..etc

I tried with serialize(), but its not working.

select from database:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script> 
<script type="text/javascript">
    $(document).ready(function(){
        $(".allbooks").change(function(){
            var allbooks = $(this).val();
            var dataString = "allbooks="+allbooks;
            $.ajax({
                type: "POST",
                data: dataString,
                url: "get-data.php",
                success: function(result){
                    $("#show").html(result);
                }
            });

        });
    });
</script>

</head>
<body>
 <?php
    define("HOST","localhost");
    define("USER","root");
    define("PASSWORD","");
    define("DATABASE","hotel");
    $euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);

  $selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
   $resultRooms = mysqli_query($euConn,$selectRooms);
     if (mysqli_num_rows($resultRooms) > 0) {
    echo "<div id='reserved' align='center'>";
   While ($row = mysqli_fetch_array($resultRooms)) {
    echo $row[1];
    echo $row[0];
?>

<select name="allbooks" id="allbooks">
<option name="years">Choose</option>
<?php

for($i=1; $i<=19; $i++)
{
    echo "<option value=".$i.">".$i."</option>";
}
?>
 </select><br />

<?php }

 }

else
echo "<h4>nothing in the db</h4></div>";
?>
<div id="show">
</div>
</body>
</html>

and getting the results:

if(!empty($_POST["allbooks"])) {
var_dump($_POST);
    $id = 2;
    //echo $_POST['modelS'];
    $room = $_POST['allbooks'];
    $sql2 = "UPDATE proba SET room='$room' WHERE id_reservation='$id'";
    $query = mysqli_query($euConn, $sql2);
var_dump($query);
}

How to change, or what would be a simple solution? Thanks for the help.

</div>
  • 写回答

1条回答 默认 最新

  • drxp993551 2016-10-19 23:40
    关注

    You have multiple select elements on the rendered page with the id allbooks That's wrong, IDs must be unique. You'll want to change those to a class and use $(".allbooks").change(function(){ ....

    As far as sending the row id to the server with the update, you'll need to first add the row id to the select box so you can retrieve it later, something like '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"> would work.

    I would also recommend splitting the work up into several functions to better organize your code (classes would be even better)

    It's hard to test without access to the DB, but this should do it for you. Note that I have the update function on the same page and updated the ajax url property to '' which will send the data to a new instance of the current page to handle the update.

    <?php
    require_once ("db_config.php");
    
    
    function updateRoom($euConn, $newRoomVal, $id)
    {
        $stmt = $euConn->prepare("UPDATE proba SET room=? WHERE id_reservation=?");
        $stmt->bind_param('ii', $newRoomVal, $id);
        /* execute prepared statement */
        $stmt->execute();
        /* close statement and connection */
        $affectedRows = mysqli_stmt_affected_rows($stmt) > 0;
        $stmt->close();
        return $affectedRows;
    }
    function getRooms($euConn)
    {
        $selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
        $resultRooms = mysqli_query($euConn,$selectRooms);
        $rows = mysqli_fetch_all($resultRooms,MYSQLI_ASSOC);
        return count($rows) < 1 ? '<h4>nothing in the db</h4></div>' : createSections($rows);
    }
    
    function createSections($rows)
    {
        $sections = [];
        foreach( $rows as $row){
            $options = [];
            for ($i = 1; $i <= 19; $i++)
                $options[] = "<option value=" . $i . ">" . $i . "</option>";
            $options = implode('', $options);
            $select = '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"><option value="">Choose</option>' . $options . '</select><br/>';
            // .. build all your other row elements here....
            $section = 'some other compiled html'.$select;
            $sections[]=$section;
        }
        return implode('', $sections);
    }
    
    $euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE); 
    
    if(isset($_POST["allbooks"]) && $_POST["allbooks"] !='') {
        $updated = updateRoom($euConn,$_POST["allbooks"],$_POST["rowId"] );
        echo json_encode(['success'=>$updated]);
        exit;
    }
    
    $pageSections = getRooms($euConn);
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $(".allbooks").change(function(){
                    var $this = $(this);
                    var allbooks = $this.val();
                    var rowId = $this.data('row-id');
                    var dataString = "allbooks="+allbooks+'&rowId='+rowId;
                    $.ajax({
                        type: "POST",
                        data: dataString,
                        url: "",
                        success: function(result){
                            $("#show").html(result);
                        }
                    });
    
                });
            });
        </script>
    </head>
    <body>
    
    <div id='reserved' align='center'>
    <?php echo $pageSections ?>
    <div id="show">
    </div>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题