我的RESTful API没有更新数据库,但是ajax返回成功
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我的RESTful API没有更新数据库,但是ajax返回成功相关的知识,希望对你有一定的参考价值。
我在本教程之后构建了一个简单的API here当用户点击房间时,系统会提示他们是否需要清理房间,如果用户点击是,则会向我的API的更新部分发出ajax请求。请求返回成功,但由于某种原因,数据库未更新。我知道连接数据库没有问题,因为我可以从数据库中读取信息没问题。下面是调用前端的一小段片段。
//loop through room cells and add click listener
var roomCells = document.getElementsByClassName("zui-sticky-col");
for (i=0; i<roomCells.length; i++) {
$(roomCells[i]).attr('data-room', i);
$(roomCells[i]).on('click tap', function() {
cleanFlag(this);
});
}
//destroy modal
$("body").on('click tap', '#closeIt', function() {
destroyModal();
});
//destroy modal
$("body").on('click tap', '.no', function() {
destroyModal();
});
//add clean event
$("body").on('click tap', '.yes', function() {
addClean();
});
//remove clean event
$("body").on('click tap', '.yesClean', function() {
removeClean();
});
//function to schedule clean flag
function cleanFlag($this) {
var attribute = $this.getAttribute("data-room");
roomClean = attribute;
$("body").addClass("lock");
$(".zui-scroller").addClass("lock");
$("body").append("<div class='overlay'></div>");
$("body").append("<div class='modal'></div>");
$(".modal").append("<p class='close'><i id='closeIt' class='far fa-times-circle fa-2x'></i></p>");
if (! $('[data-room='+roomClean+']').find('.fa-exclamation-circle').length) {
$(".modal").append("<p class='modalTxt'>Does This Room Need to Be Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yes'>Yes</div>");
}
else {
$(".modal").append("<p class='modalTxt'>Has This Room Been Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yesClean'>Yes</div>");
}
}
// function to add clean flag
function addClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "1"}),
success : function(data) {
$('[data-room='+roomClean+']').append('<br><i class="fas fa-exclamation-circle"></i>');
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
// function to remove clean flag
function removeClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "0"}),
success : function(data) {
$('[data-room='+roomClean+'] i').remove('.fa-exclamation-circle');
$('[data-room='+roomClean+'] br').remove();
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
// destroy modal
function destroyModal() {
$(".modal").remove();
$(".overlay").remove();
$("body").removeClass("lock");
$(".zui-scroller").removeClass("lock");
}
//function to schedule clean flag
function cleanFlag($this) {
var attribute = $this.getAttribute("data-room");
roomClean = attribute;
$("body").addClass("lock");
$(".zui-scroller").addClass("lock");
$("body").append("<div class='overlay'></div>");
$("body").append("<div class='modal'></div>");
$(".modal").append("<p class='close'><i id='closeIt' class='far fa-times-circle fa-2x'></i></p>");
if (! $('[data-room='+roomClean+']').find('.fa-exclamation-circle').length) {
$(".modal").append("<p class='modalTxt'>Does This Room Need to Be Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yes'>Yes</div>");
}
else {
$(".modal").append("<p class='modalTxt'>Has This Room Been Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yesClean'>Yes</div>");
}
}
//add room flag
function addRoomFlag(data) {
for (i=0; i < data.room.length; i++) {
if(data.room[i].dirty == 1) {
$('[data-room='+i+']').append('<br><i class="fas fa-exclamation-circle"></i>');
}
}
}
// here are ajax calls *********
// make json call for room status
$.ajax({
type: "get", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/read.php",
processData: true,
data: {},
dataType: "json",
success: function (data) {
addRoomFlag(data);
}
});
// function to add clean flag
function addClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "1"}),
success : function(data) {
$('[data-room='+roomClean+']').append('<br><i class="fas fa-exclamation-circle"></i>');
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
// function to remove clean flag
function removeClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "0"}),
success : function(data) {
$('[data-room='+roomClean+'] i').remove('.fa-exclamation-circle');
$('[data-room='+roomClean+'] br').remove();
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
.zui-sticky-col {
border-bottom: 0px;
border-right: 0px;
z-index:3;
text-align: center;
height: 60px;
min-width:100%;
width: 100%;
border-bottom: 1px solid rgba(255,255,255,0.1);
}
.modal {
width:80%;
z-index: 10;
position: fixed;
top: 50%;
left:50%;
transform: translate(-50%, -50%);
background-color:white;
padding-left:.8em;padding-right:.8em;
padding-bottom: 10px;
}
.overlay {
width:100%;
height: 100%;
z-index: 9;
position: fixed;
top: 0;
left:0;
background-color: rgba(0,0,0,0.5);
}
.modal input {
-webkit-appearance: none;
border-radius:none;
display:block;
width: 95%;
margin: 0 auto;
background-color:#3d3d3d;
color: #e84118;
font-size: 18px;
font-weight: 600;
padding: 16px 0px;
border-radius: 0;
border: 0px;
text-align: center;
}
.modalTxt {
padding: 15px 0px;
margin: 0;
font-size: 18px;
color: #3d3d3d;
font-weight: 600;
text-align: center;
}
.close {
padding: 10px 10px 0px 0px;
margin: 0;
color: #e84118;
font-weight: 600;
text-align: right;
}
#closeIt {
cursor: pointer;
}
.fa-times-circle {
color:inherit;
}
.lock {
overflow: hidden;
width: 100vw;
height: calc(100vh - 61px);
}
.responseWrap {
margin-top: 10px;
display: flex;
justify-content: space-around;
}
.no, .yes, .yesClean {
padding: .8em 1em;
border-radius: 5px;
cursor: pointer;
}
.no {
background-color: red;
color:white;
}
.yes, .yesClean {
background-color: green;
color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" rel="stylesheet"/>
<div class="zui-sticky-col">Room 1</div>
<div class="zui-sticky-col">Room 2</div>
<div class="zui-sticky-col">Room 3</div>
<div class="zui-sticky-col">Room 4</div>
<div class="zui-sticky-col">Room 5</div>
<div class="zui-sticky-col">Room 6</div>
<div class="zui-sticky-col">Room 7</div>
<div class="zui-sticky-col">Room 8</div>
<div class="zui-sticky-col">Room 9</div>
<div class="zui-sticky-col">Room 10</div>
<div class="zui-sticky-col">Room 11</div>
<div class="zui-sticky-col">Room 12</div>
以下是我的API的一部分,与此问题有关
// Rooms class (rooms.php)
<?php
class Rooms{
// database connection and table name
private $conn;
private $table_name = "********";
// object properties
public $room;
public $dirty;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// read rooms
function read(){
// select all query
$query = "SELECT
p.room, p.dirty
FROM
" . $this->table_name . " p
ORDER BY
p.room";
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
return $stmt;
}
// update the room
function update(){
// update query
$query = "UPDATE
" . $this->table_name . "
SET
dirty =:dirty
WHERE
room =:room";
// prepare query statement
$stmt = $this->conn->prepare($query);
// sanitize
$this->dirty=htmlspecialchars(strip_tags($this->dirty));
$this->room=htmlspecialchars(strip_tags($this->room));
// bind new values
$stmt->bindParam(':dirty', $this->dirty);
$stmt->bindParam(':room', $this->room);
// execute the query
if($stmt->execute()){
return true;
}
return false;
}
} ?>
// update (update.php) this is the main driver
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// include database and object files
include_once '../config/database.php';
include_once '../objects/rooms.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$rooms = new Rooms($db);
// get id of room to be edited
$data = json_decode(file_get_contents("php://input"));
// set ID property of product to be edited
$rooms->room = $data->room;
// set product property values
$rooms->dirty = $data->dirty;
// update the product
if($rooms->update()){
// set response code - 200 ok
http_response_code(200);
}
// if unable to update the room, tell the user
else{
// set response code - 503 service unavailable
http_response_code(503);
}
?>
我有一种感觉,这个问题与我用ajax打电话来推动房间状态有关,但我不确定。我知道这是一个代码墙,几乎没有什么可以继续,但任何帮助都非常感谢。
以上是关于我的RESTful API没有更新数据库,但是ajax返回成功的主要内容,如果未能解决你的问题,请参考以下文章
ArcGIS API for JavaScript 4.4学习笔记[新] AJS4.4和AJS3.21新特性
RESTful API 设计:更新 (PUT) 中的不可更改数据是不是应该是可选的?