Else condition won't run - javascript

I know the title is very annoying but anyways I start my question. I have created a function in a class that's kinda a multi-purpose one. I gave it a parameter which is of boolean type and of course only accepts "true" and "false" as values. Next, I am calling out that function through another PHP file on which the data is posted through ajax and that ajax is called through a button on my HTML page. Let me demonstrate it as a diagram:
I hope you've understood my program flow, now let's come to the code or in other words here is what I've tried:
HTML Page's button:
document.write('<span class="pull-right" style="margin-top: -30px; margin-right: 20px;"><button id="accept_offer" class="btn btn-success" onclick="setPostOfferAcceptance(32);">Accept Offer</button></span>');
AJAX Page:
<?php
require_once '../../Classes/MyClass.php';
$offer_id = $_POST["id"];
$acceptance = $_POST["acceptance"];
$accepted = MyClass::SetOfferAcceptance($offer_id, $acceptance);
if($accepted) $data["status"] = "success";
else $data["status"] = "error";
echo json_encode($data);
?>
MyClass's Function:
public static function SetOfferAcceptance($offerId, $acceptance) {
if(Utilities::IsValid($offerId) && Utilities::IsValid($acceptance)) {
Database::OpenConnection();
$offerId = Utilities::SafeString(Database::$databaseConnection, $offerId);
$acceptance = Utilities::SafeString(Database::$databaseConnection, $acceptance);
$query = "";
if($acceptance == true) {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
$query->bind_param("i", $offerId);
$result = $query->execute();
Database::CloseConnection();
if($result) return 1; else return -1;
}
}
And sorry, but finally, here's my javascript function that posts the data to the AJAX page:
function setPostOfferAcceptance(offer_id) {
if($("#accept_offer").text() == "Accept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: true}, function(data){
if(data.status == "success") {
$("#acceptedOfferModal").modal("show");
setTimeout(function(){ $("#acceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Unaccept Offer");
console.log(data.status);
}
}, 'json');
} else if($("#accept_offer").text() == "Unaccept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: false}, function(data){
if(data.status == "success") {
$("#unacceptedOfferModal").modal("show");
setTimeout(function(){ $("#unacceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Accept Offer");
console.log(data.status);
}
}, 'json');
}
}
EDIT: I forgot to post the JS code. But I've updated it now. Please consider it. Thanks.
The problem is that the function SetOfferAcceptance() is never running the else condition which is that if $acceptance is not equal to true.
Why? Can anyone please point out my mistake.
Thanks.

If acceptance is boolean then use the following if...else, i.e. with tripple equals $acceptance === true:
// In AJAX page
if ($acceptance === true) {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
Please reference: "How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?"
Update:
Either check for $acceptance value in SetOfferAcceptace, or pass in boolean value to SetOfferAcceptance. Example with latter:
$offer_id = $_POST["id"];
$acceptance = false;
if (isset($_POST["acceptance"]) && $_POST["acceptance"] == 'accepted') {
$acceptance = true;
}
$accepted = MyClass::SetOfferAcceptance($offer_id, $acceptance);

Thanks you all for your answers but I figured out another alternative. That was instead of making $acceptance a boolean I made it a string and converted my JS code into:
function setPostOfferAcceptance(offer_id) {
if($("#accept_offer").text() == "Accept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: "accepted"}, function(data){
if(data.status == "success") {
$("#acceptedOfferModal").modal("show");
setTimeout(function(){ $("#acceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Unaccept Offer");
console.log(data.status);
}
}, 'json');
} else if($("#accept_offer").text() == "Unaccept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: "unaccepted"}, function(data){
if(data.status == "success") {
$("#unacceptedOfferModal").modal("show");
setTimeout(function(){ $("#unacceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Accept Offer");
console.log(data.status);
}
}, 'json');
}
}
And my class's function into:
public static function SetOfferAcceptance($offerId, $acceptance) {
if(Utilities::IsValid($offerId) && Utilities::IsValid($acceptance)) {
Database::OpenConnection();
$offerId = Utilities::SafeString(Database::$databaseConnection, $offerId);
$acceptance = Utilities::SafeString(Database::$databaseConnection, $acceptance);
$query = "";
if($acceptance == "accepted") {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
$query->bind_param("i", $offerId);
$result = $query->execute();
Database::CloseConnection();
if($result) return 1; else return -1;
}
}
And that worked! :)
Thanks again #vee.

If I am not mistaken your issue stems from automatic type casting.
if($result) return 1; else return -1; // both of these evaluate to boolean true because -1 is an integer
if($result) return 1; else return 0; // evaluates to true/false respectively
if($result) return true; else return false; // evaluates to true/false respectively
The last line is what you should honestly be using.

Related

I want to do something when the beforeunload is canceled

my english is not good. sorry.
I want developing a CMS with php. And I want to change the on_desk database column to 1 when the post edit page is opened and the on_desk column to be 0 when exiting same page
By doing this while you are in the Edit Post window tab. I want to prevent the same page from opening in a new window.
I used the following solution. But sometimes it doesn't work well.
For example, when I cancel the dialog, it does not work well
Do you have another solution? For example, the way not to use beforeunload.
Javascript|jQuery:
function clearDesk(){
$.post('clearOnDesk.php',{
"id":parseInt($('body').attr('data-pageId')),
}, function(){
$('body').attr('data-desk',1)
});
}
function setDesk(){
$.post('setOnDesk.php',{
"id":parseInt($('body').attr('data-pageId')),
}, function(){
$('body').attr('data-desk',2)
});
}
setDesk();
const beforLoadFunc = function beforLoadFunc () {
clearDesk();
if(parseInt($('body').attr('data-desk')) == 1){
setTimeout(() => {
window.addEventListener('mousemove', (e) => {
setDesk();
});
}, 1000);
}
}
window.addEventListener('beforeunload', function onBeforeUnload(e) {
setTimeout(beforLoadFunc, 500);
const dialogText = 'are you sure?';
e.returnValue = dialogText;
return dialogText;
});
clearOnDesk.php
if($_POST)
{
$id = (int)$this->post('id');
if($id && $id != '')
{
$w['id'] = $id;
} else die("die!");
$d['on_desk'] = 1;
$this->db->update('post',$d,$w,["i","i"]);
//update on_desk to 0 for (post row) in database by (pageId).
//by PHP Prepared Statements
}
setOnDesk.php
if($_POST)
{
$id = (int)$this->post('id');
if($id && $id != '')
{
$w['id'] = $id;
} else die("die!");
$d['on_desk'] = 2;
$this->db->update('post',$d,$w,["i","i"]);
// update on_desk to 1 for (poster row) in database by (pageId).
//by PHP Prepared Statements
}

How to validate form based on values and submit call out to another page accordingly?

How can I pause submission so that I can validate, check values, and possibly submit an xhtml callout based on the choices all before allowing the form to finally submit?
Have tried using various jquery methods found on here, using callbacks, setting timeouts, and holding in a while loop until everything's done. A lot of the alerts found in the code are only for troubleshooting/tracing purposes.
function completeTicket() {
alert("fnOpenDiag Called");
$("#dialog-confirm").html("Auto create return eTicket?");
// Define the Dialog and its properties.
$("#dialog-confirm").dialog({
resizable: false,
modal: true,
title: "Auto create return eTicket?",
height: 250,
width: 400,
buttons: {
"Yes": function () {
var quickissue = "Return <?php echo ($ticketRow['items_count'] >= 1 ? $ticketRow['items'] : 'Computer'); ?>";
var selectedLocation2 = <?php echo ($ticketRow['Location_ID'] == '' ? 0 : $ticketRow['Location_ID']); ?>;
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null) {
alert ("This browser does not support XMLHTTP!");
}
var url="xhtmlCallOut_QuickEticket.php?callerID=pc_ticket_detail&selectedLocation_ID=" + selectedLocation2 + "&tboxIssue=" + quickissue;
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
if (xmlhttp.readyState==4){
if (xmlhttp.responseText != 0){
alert(xmlhttp.responseText);
}
}
alert("ticket success");
return true;
$(this).dialog('close');
//callback(true);
//callback();
},
"No": function () {
return true;
$(this).dialog('close');
//callback(false);
//callback();
}
}
});
}
function checkForm() {
alert("checkform called");
if(document.getElementById('assocCompany').selectedIndex == 0) {
alert('Please associte this company with a known company name\nfrom the drop list.');
document.getElementById('assocCompany').focus();
e.preventDefault();
return false;
}
else if(document.getElementById('assignTech').selectedIndex == 0 && document.getElementById('status').selectedIndex >= 2){
alert('You must define a technician first!');
document.getElementById('assignTech').focus();
e.preventDefault();
return false;
}
else if(RegisterForm.elements['status'].value == 3 && RegisterForm.elements['tboxreaspend'].value.length < 3){
alert('You must give a reason for this ticket being changed to pending');
document.getElementById('tboxreaspend').focus();
e.preventDefault();
return false;
}
else if(RegisterForm.elements['tboxissue'].value.length < 3){
alert('You must give a description of the issue');
document.getElementById('tboxissue').focus();
e.preventDefault();
return false;
}
else {
pc_ticketdetail.actionbutton.disabled=true;
return false;
}
}
function showPendingReason() {
var y = document.getElementById("status");
var val = y.options[y.selectedIndex].value;
if (val == 3) {
$('#trReasPend').show();
} else {
$('#trReasPend').hide();
}
}
function submitForm() {
alert("submitform called");
var x = document.getElementById("status");
var valx = x.options[x.selectedIndex].value;
alert("statval is " + valx);
if (valx == 4) {
if (completeTicket()) {
e.preventDefault();
return false;
alert("complete ticket done");
} else {
e.preventDefault();
return false;
}
} else {
if (checkForm()) {
e.preventDefault();
return false;
alert("checkform done");
} else {
alert("checkform FALSE return");
e.preventDefault();
return false;
}
}
}
<div id="dialog-confirm"></div>
<form action="<?php $_SERVER['PHP_SELF']; ?>" name="pc_ticketdetail" id="pc_ticketdetail" method="post" onSubmit="return submitForm();">
<select name="status" id="status" onChange="javascript:showPendingReason();">
<option<?php if($ticketRow['status'] == 1){ echo ' selected'; } ?> value="1">New</option>
<option<?php if($ticketRow['status'] == 2){ echo ' selected'; } ?> value="2">Bench</option>
<option<?php if($ticketRow['status'] == 3){ echo ' selected'; } ?> value="3">Pending</option>
<option<?php if($ticketRow['status'] == 4){ echo ' selected'; } ?> value="4">Finished</option>
<?php if($ticketRow['status'] == 5){
echo '<option selected value="5">Closed/Deleted</option>';
} ?>
</select>
It currently seems to step through as expected except the "completeTicket" and "checkForm" functions are either not being called or not returning correctly. The form simply submits and closes when they should fail validation or open the modal dialogue and ask to create return ticket.
Take a look on the (async - await) function in javaScript.
async function
your checkForm() never return false so is your completeTicket() never return true. you can initially define a variable as false and make it true if it meets a specific condition then return the variable to the main function.
<script>
function c(){
let isTrue = false;
if(condition){
isTrue = true;
}
return isTrue;
}
function d(){
if(c()){
alert("c returned true");
} else{
alert("c returned false");
}
}
</script>
If you remove the alerts from under the return statements, that would help you in tracing the problem, because no code will run after you return from a function. Same thing for $(this).dialog('close').
And I think that you should capture the event object before using it in e.preventDefault() so try to remove the onSubmit attribute from the form and adding the listener through jQuery like so :
$(YOUR_FORM_SELECTOR).submit(function(e) {
// here you access to the e Object
})
I don't know if that related to the problem you have, Try describing what's happening exactly when you run the code.

Mistake in transferring between PHP and JavaScript

I have a PHP file and JavaScript file.
JavaScript transfers 3 variables into PHP file, PHP file transfers the result into JavaScript. The process is working and gives me the right result, however as a last action in JavaScript when I checking the result it is give me false instead of true. So please help me to find out what is wrong.
PHP:
if ((isset($_POST['st'])) && (!empty($_POST['st'])))
{
$status=$_POST['st'];
switch($status)
{
case '0': {
break;
}
case "1": {
$login = $_POST['login'];
$pas = $_POST['pas'];
check($login,$pas);
break;
}
}
exit;
}
function check ($login,$pas) {
include "php/log_bd.php";
$result = mysql_query("SELECT * FROM users WHERE Login='$login'",$db); //I know, i know, that it is dangerous in case of SQL injection, but I use it for educational example.
$row = mysql_fetch_array($result);
if (empty($row))
{
exit('er');
}
if ($row['Pas']!= $pas)
{
exit('er');
}
exit(0);
}
JavaScript:
$(document).on("click","input[name=door_open]", function () {
var login = $("input[name=login]").val();
var pas = $("input[name=pas]").val();
$.post("index.php",{ st:1, login:login , pas:pas} ,function(data)
{
alert (data); // I have 'er'
if (data == 'er')
{
alert ("Sorry incorrect data");
return false;
}
else
{alert (data);}
});
return false;
});
So It give me in JavaScript file 'er' result but when I check data == 'er', it told me that it is false.
As was suggested I add some some log console comands

php session_id change on header redirect

What I am trying to do is increment the value inside the COOKIE in every redirect... but every time I check if the cookie exists it doesn't.
I try to do it with a SESSION also, but the session_id changes in each redirect (I am guessing that the redirect create a new session for some reason )
This is my code
<script language="javascript">
var popexurl = "<?php echo $PopExitUrl ?>";
if(popexurl != ""){
(function() {
setTimeout(function() {
<?php
if (isset($_COOKIE["count"]))
{
//cheak user refreshes
$cookie = (int)++$_COOKIE['count'];
setcookie("count", $cookie, time()+3600);
}
else
{
setcookie("count", 1, time()+3600);
$cookie=0;
}
?>
var __redirect_to = '<?php echo $PopExitUrl; ?>';//
var _tags = ['button', 'input', 'a'], _els, _i, _i2;
for(_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for(_i2 in _els) {
if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {window.onbeforeunload = function(){};}
}
}
window.onbeforeunload = function() {
window.scrollTo(0,0);
document.getElementById('ExitBackDiv').style.display = 'block';
document.getElementById('ExitDiv').style.display = 'block';
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function()
{
window.location = __redirect_to;
}, 500);
},5);
<?php
if ($PopupMessage == ""){
$PopupMessage= "\\n**********************\\nWAIT! WAIT! WAIT! WAIT!\\n\\n**********************\\n\\nDont Miss This LAST CHANCE to become Financially Secure and CHANGE YOUR Lifestyle!!!\\n\\n...Click STAY ON THIS PAGE to activate your LIMITED time offer!";}
?>
var popmsg = "<?php echo $PopupMessage ?>";
if (navigator.userAgent.indexOf("Firefox")!=-1)
{
//setTimeout('window.location="'+__redirect_to+'"', 10);
window.alert(popmsg);
return popmsg;
}
else
{
return popmsg;
}
}
}, 500);
})();
}
</script>
session_start(); creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
PHP: session_start()

Check if a user Is fan of a Facebook page

After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.
function pageFan()
{
FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
showAlert(response);
});
}
function showAlert(response)
{
if (response == true) {
return 'like the Application.';
} else {
return "doesn't like the Application.";
}
}
var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
This question has already been answered.
Relevant Javascript:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.
function showAlert(response)
{
if (response == true) {
document.getElementById('debug').innerHTML = 'like the Application.';
} else {
document.getElementById('debug').innerHTML = "doesn't like the Application.";
}
}

Categories

Resources