单击复选框时,我尝试同步更新数据库。 我决定使用aJax但它似乎并不认识ajax。
代码: 将成为Switch_Active(this.id)函数的元素
...
<div class='switch'>
<label>
Deactivate
<br>
<input name='switch_Activate1'onclick='Switch_Activate(this.id)' type='checkbox'>
<span class='lever'></span>
<br>
Activate
</label>
</div>
...
THE SCRIPT
<script type="text/javascript">
function Switch_Activate(id) {
if (!document.getElementById(id).checked) {
var projectID = id;
var Activation_Status = 1;
var dataString = "projectID=" + projectID + "&Activation_Status=" + Activation_Status ;
$.ajax({
type: "POST",
url: "ajax/switchchange.php",
data: dataString,
cache: false,
dataType: "json",
success: function (data) {
alert("asd1");
}
});
}
else{
var projectID = id;
var Activation_Status = 1;
var dataString = "projectID=" + projectID + "&Activation_Status=" + Activation_Status ;
$.ajax({
type: "POST",
url: "ajax/switchchange.php",
data: dataString,
cache: false,
dataType: "json",
success: function (data) {
alert("asd2");
}
});
}
}//
</script>
switchchange.php
<?php
include("../../connection/connection.php");
echo"<script type='text/javascript'>alert('php in');</script>";
$projectID = $_POST['projectID'];
$Account_Status = $_POST['Activation_Status'];
$sql = "update tblProject set projectStatus = '$Account_Status' where projectID = '$Account_Status'";
$stmnt = sqlsrv_query($db, $sql);
?>
CONNECTION
<?php
//Database Connection
try{
$db = new PDO("sqlsrv:Server=AJ-PC\SQLEXPRESS;Database=RealEstate_DB", "", "");
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOExceptio $e){
echo $e->getMessage();
die();
}
答案 0 :(得分:1)
我会以这种方式重写您的代码,确保您按照以下步骤操作:
this.id
,如果您只需使用this
即可获得有关该元素对象的所有信息dataString
,然后将数据传递给AJAX一次。return false
因为点击复选框不会触发任何其他内容。这是我的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<input id="someID" name='switch_Activate1' onclick='Switch_Activate(this)' type='checkbox'>
<script>
function Switch_Activate(checkbox) {
var dataString = {
'project_ID': checkbox.id,
'Activation_Status': checkbox.checked
};
$.ajax({
type: "POST",
url: "ajax/switchchange.php",
data: dataString,
cache: false,
dataType: "json",
done: function (data) {
alert(data.message);
if (data.response) {
// your success code
} else {
// your error code
}
}
});
}
</script>
更新
我刚刚意识到您的AJAX调用已设置为接受JSON dataType: "json"
但您的PHP未输出JSON。您需要将所有输出转换为JSON,因此在您的情况下,您可以执行以下操作:
<?php
// ... your Database UPDATE code...
$result = array(
"response" => TRUE,
"message" => "some message"
);
header("Content-type: application/json");
echo json_encode($result);