[英]use checkbox with ajax to update database
So, I am try to update the fields in my database (id[int], status[boolean]) using a checkbox with Ajax.因此,我尝试使用带有 Ajax 的复选框来更新我的数据库中的字段(id[int]、status[boolean])。 This should be done without refreshing the page and not using a submit button.
这应该在不刷新页面和不使用提交按钮的情况下完成。 I have tried multiple tutorials and non seems to work for me.
我尝试了多个教程,非似乎对我有用。 To name a few: Ajax updating database when a checkbox is checked , checkbox on change ajax call , update database with checkbox
仅举几例: 选中复选框时 Ajax 更新数据库、 更改 ajax 调用复选框、 使用复选框更新数据库
Please I really need help with this one been on this for days.请我真的需要帮助这个已经好几天了。 This is my attempt at it:
这是我的尝试:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="jquery.min.js"></script>
</head>
<body>
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1"/>
<script type="text/javascript">
$("#action1").change(function () {
var value = $(this).val();
$.ajax({
type: "POST",
url: "update.php",
async: true,
data: {
action1: value // as you are getting in php $_POST['action1']
},
success: function (msg) {
alert('Success');
if (msg != 'success') {
alert('Fail');
}
}
});
});
</script>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "api";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
if($_POST['action1']==1){ //as used variable name "value" in ajax post data
$sql = "UPDATE toggle SET status = '1' WHERE id = '1'"; //query was incomplete and missing ";"
echo 'success';
}
else{
$sql = "UPDATE toggle SET status = '0' WHERE id = '1'"; // missing ";"
echo 'success';
}
$result=$conn->query($sql);
?>
Your update file returns 'success' no matter what data is sent to it.无论发送什么数据,您的更新文件都会返回“成功”。 Try it this way:
试试这个方法:
if($_POST['action1']==1){ //as used variable name "value" in ajax post data
$sql = "UPDATE toggle SET status = '1' WHERE id = '1'";
echo 'success';
}
else{
$sql = "UPDATE toggle SET status = '0' WHERE id = '1'";
echo 'fail';
}
$result=$conn->query($sql);
?> ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.