gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:07:47 25 4
gpt4 key购买 nike

我已经认真研究过这个问题,但我无法理解 AJAX 与 PHP 的配合。

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

<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;

?>

希望对您有帮助。

关于javascript - 如何使用 AJAX 将 DropDown 保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com