Reputation: 709
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. 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
// 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. I know this is a wall of code with little to go on but any help is greatly appreciated.
Upvotes: 0
Views: 855
Reputation: 511
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");" 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)
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();
}
Upvotes: 1