简体   繁体   English

我的RESTful API没有更新数据库,但是ajax返回成功

[英]My RESTful API isn't updating the database, but ajax returns success

I've built a simple API following this tutorial here When the user clicks on a room they're prompted with does the room need to be cleaned, if the user taps yes, an ajax request is made to the update section of my API. 我在这里按照本教程构建了一个简单的API 当用户单击某个房间时,系统会提示他们是否需要打扫房间,如果用户单击“是”,则会向我的API的update部分发出ajax请求。 The request returns success, but for some reason the database isn't updated. 该请求返回成功,但是由于某种原因数据库未更新。 I know there is no problem connecting to the database as I can read information from the database no problem. 我知道连接到数据库没有问题,因为我可以从数据库读取信息没有问题。 Below is a small snippet of the front-end where the calls are made. 以下是拨打电话的前端的一小段代码。

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

Below is a portion of my API that pertains to this issue 以下是我的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);

}
?>

I have a feeling this issue is some how related to the call I make with ajax to push the room status but I'm not sure. 我有一个感觉,这个问题与我用ajax发出的推送房间状态的呼叫有什么联系,但我不确定。 I know this is a wall of code with little to go on but any help is greatly appreciated. 我知道这是一堵代码墙,几乎没什么可做的,但是对您的帮助非常感谢。

As explained in the comment above, the issue there is the code 如上面评论中所述,问题在于代码

var attribute = $this.getAttribute("data-room");
roomClean = attribute;

and

var temp = roomClean +1;

since "$this.getAttribute("data-room");" 因为“ $ this.getAttribute(”数据室“);” return a string, you need to parse it in number before the add. 返回一个字符串,您需要在添加之前解析其编号。

So the code becomes: 因此,代码变为:

var temp = parseInt(roomClean)+1;

For further note, I would change the functions: 为了进一步说明,我将更改功能:

addClean() | removeClean()

with just another parameterized function (with a boolean or a number 1/0 as you whish) 仅带有另一个参数化函数(您希望使用布尔值或数字1/0)

function cleanFunction(clean) {

  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": clean}),
    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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM