jQuery if statement broken? - javascript

I have a php webpage where a user enters their details into a form and after submitting two sections, named profile and images, must then appear. Here is the javascript code:
jQuery(document).ready(function($) {
var registered = <?php echo $registered; ?>;
alert(registered);
if (registered == 'false') {
$("#profile").hide();
$("#images").hide();
}
if (registered == 'true') {
alert('hello');
$("#profile").show();
$("#images").show();
}
});
For some reason it does not go into the if statement at all, even though the alert shows registered's value as true. What could be the problem here?

var registered = <?php json_encode($registered) ?>
if(registered == true) {
alert(registered);
$("#profile").hide();
$("#images").hide();
} else {
alert('hello');
$("#profile").show();
$("#images").show();
}

You are mixing up the string 'true' with the boolean true. Try a version that uses booleans from start to finish instead:
var registered = <?= json_encode($registered) ?>;
if (registered) {
$("#profile").hide();
$("#images").hide();
} else {
$("#profile").show();
$("#images").show();
}
Edit - Thanks to Jon in another comment for suggesting using json_encode.

use JSON.parse() Takes a well-formed JSON string and returns the resulting JavaScript object.
//JSON.parse(registered);
var registered = <?php echo $registered; ?>;
if (!(JSON.parse(registered))) {
$("#profile").hide();
$("#images").hide();
}
else {
$("#profile").show();
$("#images").show();
}

Remove the quotes and try
jQuery(document).ready(function($) {
var registered = <?php echo $registered; ?>;
alert(registered);
if (registered == false) { //Remove the quotes
$("#profile").hide();
$("#images").hide();
}
if (registered == true) { //Remove the quotes
alert('hello');
$("#profile").show();
$("#images").show();
}
});

Reason in this demo.
var registered = true;
alert(registered == 'true'); //return false
alert(registered == 'false'); //return false
In JavaScript data type comparison is a bit inconsistent. So always try to compare same data-types.
so try:
var registered = true;
alert(registered == true); //return true
alert(registered == false); //return false
Change your code to:
if (registered) {
alert('hello');
$("#profile").show();
$("#images").show();
}
else {
$("#profile").hide();
$("#images").hide();
}

Try with this
jQuery(document).ready(function($) {
var registered = "<?php echo $registered; ?>";
alert(registered);
if (registered == false) {
$("#profile").hide();
$("#images").hide();
}
else if (registered == true) {
alert('hello');
$("#profile").show();
$("#images").show();
}
});

Related

How can I validate a hCaptcha in the same page and afterwards redirrect the answer to post/ajax.php?

I use a script written by somebody else and I don't know javascript at all.
The following usecase I want to change: if you press for a button, it will be displayed a modal with a captcha in it. After you validate the captcha, the page proceeds with some datas for ajax.php. I have the code that works for the previous captcha implemented, but I want to do it through hCaptcha.
function goShortlink(sid) {
$('#goShortlink').modal({backdrop: 'static', keyboard: false});
$('.captcha-holder').CBCaptcha({
clickDelay: 500,
invalidResetDelay: 2500,
requestIconsDelay: 1500,
loadingAnimationDelay: 1500,
hoverDetection: true,
enableLoadingAnimation: true,
validationPath: 'system/libs/captcha/request.php'
}).bind('success.CBCaptcha', function(e, id) {
validateShortlink(sid);
});
}";
and the validation path from system/libs/captcha/request.php is
<?php
session_start();
require('session.class.php');
require('captcha.class.php');
if((isset($_GET['hash']) && strlen($_GET['hash']) === 48) &&
(isset($_GET['cid']) && is_numeric($_GET['cid'])) && !isAjaxRequest()) {
CBCaptcha::getIconFromHash($_GET['hash'], $_GET['cid']);
exit;
}
if(!empty($_POST) && isAjaxRequest()) {
if(isset($_POST['rT']) && is_numeric($_POST['rT']) && isset($_POST['cID']) && is_numeric($_POST['cID'])) {
switch((int)$_POST['rT']) {
case 1:
$captcha_theme = (isset($_POST['tM']) && ($_POST['tM'] === 'light' || $_POST['tM'] === 'dark')) ? $_POST['tM'] : 'light';
header('Content-type: application/json');
exit(CBCaptcha::getCaptchaData($captcha_theme, $_POST['cID']));
case 2:
if(CBCaptcha::setSelectedAnswer($_POST)) {
header('HTTP/1.0 200 OK');
exit;
}
break;
default:
break;
}
}
}
header('HTTP/1.1 400 Bad Request');
exit;
function isAjaxRequest() {
return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
}
?>
How can I modify it for holding the modal until hCaptcha is validated and then proceeding with the validation ? I have the rest of the code as well, but I don't know if it is not important for our problem. If you need it please tell me.
Thanks for your kindness and help!
I used data-callback and it worked. After I solve the captcha, the functions go on:
<div class="h-captcha" data-sitekey="XXXX-XXX-XXX-XXX" data-callback="correctCaptcha"></div>
So i added the var correctCaptcha attribution in my javascript code on my page and now is something like:
<?php
if($proxy === false)
{
echo '<script src="static/js/simple.timer.js"></script><script async src="static/js/captcha.min.js"></script>';
$script = "var waitMsg = \"".$lang['l_145']."\";
var captchaMsg = \"".$lang['l_142']."\";
var correctCaptcha = function validateShortlink(sid){
$('#status').html('<div class=\"alert alert-info\" role=\"alert\"><i class=\"fa fa-cog fa-spin fa-fw\"></i> '+waitMsg+'</div>').fadeIn('fast');
$.post('system/ajax2.php', { a: 'getShortlink', data: sid, token: '".$token."' },
function(response) {
if(response.status == '600') {
goShortlink(sid);
$('#status').html(response.message).fadeIn('slow');
} else if(response.status == '500') {
$('#captchaBox').hide();
$('#status').html(response.message).fadeIn('slow');
} else {
$('#status').html(response.message).fadeIn('slow');
window.setTimeout(function(){window.location.replace(response.shortlink);}, 500);
}
},'json');
};
function goShortlink(sid) {
$('#goShortlink').modal({backdrop: 'static', keyboard: false});
}";
if(count($counters) > 0)
{
$script .= '$(document).ready(function(){';
foreach($counters as $counter)
{
$script .= "$('#staticTime_".$counter."').hide(); $('#short_".$counter."').startTimer({onComplete: function(element){window.location.reload();}}); $('#short_".$counter." div').css('display','inline');";
}
$script .= '});';
}
$packer = new JavaScriptPacker($script, 'Normal', true, false);
$packed = $packer->pack();
echo '<script>'.$packed.'</script>';
}
?>
Ajax2.php looks like
$sid = $db->EscapeString($_POST['data']);
$linkData = $db->QueryFetchArray("SELECT * FROM `shortlinks_config` WHERE `id`='".$sid."' AND `status`='1' LIMIT 1");
if(empty($linkData['shortlink']) || empty($linkData['password']))
{
$resultData = array('message' => '<div class="alert alert-danger" role="alert"><i class="fa fa-exclamation-triangle fa-fw"></i> '.$lang['l_482'].$_POST['data'].'</div>', 'status' => 500);
}
else
The code works well with the old captcha and without the attribution of validateShortlink to the var correctCaptcha, but now I have another problem. I think that through this attribution, correctCaptcha = function validateShortlink(sid), the POST['data'] doesn't have the form of a number, so I get in ajax2.php an error that the shortlink doesn't exist on the database when the comparison is made. I wrote an echo near the error to see how sid looks like and i have something like:
`P0_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNza2V5IjoiaHNxRWc0ZVdLUmNPTHZybGFxZ0p4djlsTlVLYktIQ2VOaUI3Mmw3VmZqa21kVDh5Q0Q5N2NoSHBHbjJ2dHdXRWU3YnU2OGtpZHB4eVpJYllzTFBDay9MMXVIZXFicVN1QTVUSWxmU2txcGU3ZnMxOUFVOGk1a0IvQ2JRUkU5ZDluL2FHZTF2amUxNnZpM085UE9PVGcwR1JyOWFsYXNMK2h2UitPWG5jcWFmVzhQNXlCU0sydm9TakhZNkVSbzJ1ZEh4TWIyQmN0bzFPZEVCdnViRjhjT3FYRVhMUXF1WTN1Z1EyVDdhR2xGK28xTkRHRGkzZVM5MXVBTmUxSVE4M1NSYkFpN253MnNVdFRzVDJyYWs0OUVGdXFHOHgzbjBhRENSMnpvZGRYSGFUUEtBLzNFTUpVVDBWU1NSRWtuVjBiY01oVktzSmF1R0pKcjlwSnJwaUl2N3NKSlJBVm9pOW5ZVGt6K3hKOTlOcHVKRG9SdDR1QmxKeW1ndWcvL0x2N3NDK2JMSnBzeENSM3U5Ly9wcnlwd3R5ZWlmZHRZNlM2UERmUG00eFNQTERwNGdnS2NUbGNqYjFkeU9ZTVFiaFEyWi8rakJkV2lZMG1QQ20yRnFRVVhoME9CdjJtNGdoRGplOUJYNm15ZUR4UFZYdEN6R214UVJOTTZrWDRlOGtZY3JqUlNzYk96OXNjaXBQL2REOHNCSzlTNjJLc2dTNkFpczM0ZnFqcXFTRHRKN0xGUjc4UlYycWlCcFQvK2JweC9hOEgwdjd6eXM5aHRYZ1lrdU5YQ0hQc0x4ZWRHek1YVWtPRTdVVjNhMzNTcVg4bFhnL0RxTFA3cFVrb3RLWU1qcjZ5OUp5cDdxME1UUWN5Zy9XN290WE5ucTlNNnRHcU4xRW9uWVAxQ1dmckZKTENyck1XVUdkb01LQy9mSmFuZE0rMzZMan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yQUZtUUQzTnp3UWxVS2Z3cmNQSHRqZWxpZWJnWXU1MkwxOTFhWG5Id09nUUtIcU53b3REZmhjeVFlMW56STFPV1M3U1pQVVZCNS9NcUNzWC84cGhlQmdwenRFNW5LWXo1QnVsTEhtSk9MWnV2RG1Ya05WRkcwL0lXTGJzY1U1OEpXYUIzRXlsTFJud1ZhN1d0RFF0NlZuNzB4a1RxK254MEEzUkVZTjREa0Z1akVVd2ZrakZTQm0vamswN21LZlRqRlp3UkZON0Vkd0UwcXEyeDNmbDRRSGlqTUg4UDVnYXVSWDl1NTR2dlpWS08xWTRsQUlEK3dLSEw4d2ZLOGlXQzNUV0t3NWMvblpXUVVES1JwSjFQeUJnOWdEOVVFQk1PZTFVVGZCNUsvcXhEYkdvUmp4SjBoU1JsSnFhNkErYUdqWnBJSHJ1aS9vZUhkM0VCTkowd1NsNEVGc2NPaGQ4OHpVUXFjWmVYaENsZW9WM2FZbGZiYnpsY0x2dG0yVTMxaEZzV1lOTXFEdFlRVE5sVUwzblRxSlVNbmM5UUlCQTVidXg3ejUwQ2NRVUNTUHg1UE1Jc09QV3Y3MllQQWg1c2NGbllvcVZCNlRMeXh3VzRZamdFYkNSMWQrdnJRbE9hbjc3Nm1DeHVLRWhvZzA1cVY2OFJuTElnOStYa0pHR0JDcUkvQ1BSbWZremplckgwM3dYN1JZMWQ4SVdmL0Fqd0IrUVRvc09aZ3dBZ2g0MytjNlkyWVRyTWFnazJIMEJoMmMwV3lVSVozdmowSmZUY09wNG4iLCJleHAiOjE2MDMxODc2NjcsInNoYXJkX2lkIjoyMzU4MDExNjcsInBkIjowfQ.fDyx5hr2vXLScCpXO5G1nzE6yH-
How can I use correctCaptcha attribution for sending the right sid, not the whole last paragraph ?
Thanks for your kindess and your help!

Trying to convert Javascript recursion to PHP (easy)

I have to convert some javascript to PHP for a school project, but there seems to be something I'm missing, because the exact same code is suddenly exiting prematurely.
for(var j=0; j<asciiArray.length;j++) {
passwordFound[location] = String.fromCharCode(asciiArray[j]);
console.log(passwordFound.join(""));
if (password === passwordFound.join("")) {
document.getElementById("password").innerHTML = 'Password: ' + passwordFound.join("");
return true;
}
else if (location < 2) {
var newlocation = location+1;
if (characterDecryptFunction(newlocation,asciiArray,passwordFound,password)) return true;
}
}
This is the PHP:
function characterDecryptFunction($index, $maxIndex, $asciiArray, $passwordFound, $password) {
for ($j=0;$j<count($asciiArray);++$j)
{
$passwordFound[$index] = chr($asciiArray[$j]);
echo "<br>" . implode("", $passwordFound);
if ($password === implode("",$passwordFound)) {
echo "<br>Password is:" . implode($passwordFound);
return true;
}
elseif ($index < $maxIndex)
{
$index = $index+1;
if (characterDecryptFunction($index,$maxIndex, $asciiArray, $passwordFound, $password) == true) return true;
}
}
return false;}
EDIT:
The javascript is called as such:
function decryptFunction() {
var x,y,z,password,asciiArray=[],passwordFound=[];
password="abc";
asciiArray.push(0);
asciiArray.push(32);
for (x=48;x!=58;x++) {
asciiArray.push(x);
}
for (y=97;y!=123;y++) {
asciiArray.push(y);
}
for (z=65;z!=91;z++) {
asciiArray.push(z);
}
characterDecryptFunction(0, asciiArray, passwordFound,password);}
And the PHP:
function decryptFunction() {
$password = $_POST["password"];
$asciiArray=array();
$passwordFound=array();
for($x=48;$x!=58;$x++)
{
array_push($asciiArray, $x);
}
for($x=97;$x!=123;$x++)
{
array_push($asciiArray, $x);
}
for($x=65;$x!=91;$x++)
{
array_push($asciiArray, $x);
}
for ($x=0;$x<count($asciiArray);$x++)
{
echo $asciiArray[$x];
}
echo $password . "<br>";
characterDecryptFunction(0, 2, $asciiArray, $passwordFound, $password); }
It seems crucial that you do not update $index, just like you do not update location in JavaScript. So change the PHP code, introducing $new_index:
$new_index = $index+1;
if (characterDecryptFunction($new_index,$maxIndex, $asciiArray, $passwordFound, $password)) return true;
When the algorithm returns from the recursive calls, i.e. when it backtracks to previous characters, it should continue where it left off. For that $index must have retained its previous value.
NB: Note that in PHP, just as in JavaScript, you don't need to compare with true in the if statement when you know the expression is a boolean.

Use data from JQuery .get function in an Else If statement

I am running a simple .get statement with JQuery:
$.get("check.php", function(data)
{
if (data == "yes")
{
$('#thisimg').attr('src' ,'yes.jpg');
}
else
{
$('#thisimg').attr('src' ,'no.jpg');
}
});
When I call an alert with data as the parameter it returns "yes", however the if statement is still not running and changing the images src.
This is my check.php file:
<?php
//connect to db here
//run sql select statement to check whether or not the value is 0 or 1
//value is saved into variable $selected, and the value is 1
if ($selected == 1)
{
echo "yes";
}
else
{
echo "no";
}
?>
Oftentimes there will be an invisible character in returned data. If you .trim data it should work:
if (data.trim() == "yes")
{
$('#thisimg').attr('src' ,'yes.jpg');
}
else
{
$('#thisimg').attr('src' ,'no.jpg');
}

Hide and Show depending on value

Does anyone know how to hide and show options under select-tag depending on a certain value from database?
Here's what I did but it doesn't work:
<script>
var a = <?php echo $row["status"]; ?>
if(a == 'To be check' || a == 'Endorsed By IT') {
$("#new").show();
} else
$("#new").hide();
</script>
Here's what's under #new:
<div id="new">
<select name="status">
<option value="Request">Request</option>
<option value="Upload">Upload</option>
</select>
</div>
As of your problem b0s3 has the answer. Besides that, I would recommend a different way to handle this problem:
Try to modify the HTML markup while rendering instead of your altering your JavaScript:
<div id="new" <?print ( in_array($row["status"], array('To be check', 'Endorsed By IT')) ? 'class="active"' : ''); ?>
[…]
</div>
You can use a CSS class like:
#new { display: none; }
#new.active { display: block; }
You can still alter the visibility later by using:
document.getElementById('new').classList.toggle('active'); // vanilla JS
$('#new').toggleClass('active'); // jQuery
The advantages are:
The element is hidden right away and won't be visible to the user if your page loads slowly (for whatever reason).
The JavaScript code could be kept and maintained separately from your template, as it doesn't have to be modified by PHP.
Missing the quotes. $row["status"] contains string. You should add the quotes properly.
<script>
var a = '<?php echo $row["status"]; ?>'; // missing the quotes here
if(a == 'To be check' || a == 'Endorsed By IT')
{
$("#new").show();
}
else
$("#new").hide();
</script>
To show/hide div using javascript, you can write like :
<script>
var a = '<?php echo $row["status"]; ?>';
if(a == 'To be check' || a == 'Endorsed By IT')
{
document.getElementById(new).style.display = 'block';
}
else
document.getElementById(new).style.display = 'none';
</script>
Try this:-
<script>
var a = '<?php echo $row["status"]; ?>';
if(a == 'To be check' || a == 'Endorsed By IT')
{
document.getElementById("new").style.display = 'block';
}
else
{
document.getElementById("new").style.display = 'none';
}
</script>
i guess you need to do it write condition in document ready method
$( document ).ready(function() {
var a = '<?php echo $row["status"]; ?>'; // missing the quotes here
if(a == 'To be check')
{
$("#new").show();
}
else
$("#new").hide();
})

jquery script dosen't works in safari

I got problem with jquery code.It somehow doesn't work in safari browser. Rest of the browsers working fine but in safari I dont know why not any solution?
Index.php - I have this code inside HEAD
<script type="text/javascript">
$(document).ready(function () {
var prilohy = <? php echo json_encode($linkpar); ?> ;
if (prilohy == "Pizza") {
$('#content_donaska_extra').show();
} else if (prilohy == null) {
$('#content_donaska_extra').show();
} else {
$('#content_donaska_extra').hide();
}
});
</script>
Remove the space between <? and php
var prilohy = <?php echo json_encode($linkpar); ?> ;
script be
$(document).ready(function () {
var prilohy = <?php echo json_encode($linkpar); ?> ;
if (prilohy == "Pizza" || prilohy == null) {
$('#content_donaska_extra').show();
} else {
$('#content_donaska_extra').hide();
}
});

Categories

Resources