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

时间:2017-09-05 15:14:18

标签: javascript php jquery sql 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);

1 个答案:

答案 0 :(得分:1)

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

12

jQuery + AJAX

nov_dec

<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> 内,您可以访问通过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.
            }
        });
    }); 
});

希望它有所帮助。