繁体   English   中英

如何使用AJAX将DropDown保存到数据库中

[英]How can I save a DropDown into a Database with AJAX

我已经非常努力地研究了这个问题,但是我无法理解使用PHP的AJAX。

这就是我所拥有的,当用户单击下拉列表时,我希望将其保存到数据库中

<select>
  <?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
   $taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
   while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
     echo " <option  value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
   }
  ?>
</select>

这是我想运行的查询:

INSERT INTO snagging (taskstatus, updated_at) 
WHERE ID = 1234 
VALUES taskStatusRow['name'], $now);

在这里,我将为您提供AJAX的总体流程。 我试图提供评论以显示控制流。

<select id="selectOption">  //******* Assign an ID
    <?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
    $taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
    while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {

        echo " <option  value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";

    }
    ?>
</select>

jQuery + AJAX

$(document).ready(function() {
    $("#selectOption").change(function(){ //** on selecting an option based on ID you assigned
        var optionVal = $("#selectOption option:selected").val(); //** get the selected option's value

        $.ajax({
            type: "POST", //**how data is send
            url: "MYPROCESSPAGE.php", //** where to send the option data so that it can be saved in DB
            data: {optionVal: optionVal }, //** send the selected option's value to above page
            dataType: "json",
            success: function(data){
                //** what should do after value is saved to DB and returned from above URL page.
            }
        });
    }); 
});

MYPROCESSPAGE.php ,您可以访问通过AJAX传递的数据,例如:

<?php

$selectedOptionVal = $_POST['optionVal'];

//DB CONNECTION STEPS
.
.
.
// You are trying to "UPDATE" a table data based on some ID and not inserting. Included both operations

// If you are INSERTING A new table entry, use below code.
//INSERT INTO snagging (taskstatus, updated_at) VALUES ('$selectedOptionVal', 'Now()');

// If you are UPDATING an existing table entry, use below code.
//UPDATE snagging SET taskstatus = '$selectedOptionVal', updated_at = 'Now()' WHERE ID = 1234;

?>

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM