javascript variable seems to be zero but no - javascript

I have problem with recognizing variable and defining if statement dont know why. So...
$.ajax({
type: "POST",
url: "check.php",
success: function(response){
alarmvar = response;
if(alarmvar !== 0){
alert(alarmvar+"aaaaag");
}
}
});
and in check.php file:
$rowsw = mysql_num_rows($query);
echo "".$rowsw."";
variable is always defined not like 0 even if mysql_num_rows returns 0
alert is always shown and alarmvar variable causes next line in alert box.
Where is the problem?

The problem is you check if alarmvar is 0 value and number type. The operator !== check value and type. When mysql_num_rows is 0, you are checking "0" !== 0, and return true because the type is different. Alternatives:
if(alarmvar !== "0"){
alert(alarmvar+"aaaaag");
}
Or (Not recomended)
if(alarmvar != 0){
alert(alarmvar+"aaaaag");
}
And I recomended you use var to declare alarmvar, if not, alarmvar is in global scope.
var alarmvar = response;

Related

Can't enter on if statement

I'm facing a problem with a jquery script. Can't enter on an if statement.
Can someone explain me why I cant enter on if (partner_type_id === 1) even if the value is 1?
$(document).ready(function(){
$('#holder_0_partner_nr').change(function(){
var partner_type_id = $("#holder_0_partner_type_id").val();
var partner_nr = $("#holder_0_partner_nr").val();
console.log(partner_type_id);
console.log(partner_nr);
if (partner_type_id === 1)
{
$.ajax({
url: '{{ route('sgc.contracts.create.get.occ.person.data') }}',
type: 'get',
data: { partner_nr: partner_nr },
success: function(response) {
if (response !== false)
{
let data = JSON.parse(response);
$("#holder_0_name").val(function() {
return data.name;
});
}
}
});
}
});
});
are you sure it is a number? try parseInt(partner_type_id) === 1 OR partner_type_id === '1'?
.val() can return a number, string or array
In this case:
if (partner_type_id === 1) with triple ===(strict check), will only be true if both the value and type is equal.
Since you're comparing to a number you must make sure partner_type_id is also a number and not a string containing "1".
Either parse your variable correctly or use double ==

TypeError: Cannot read property of null

I get the error in the title even though I have tried all the solutions. About the value of null;
If my code is ;
Output: TypeError: Cannot read property of null
case '!facebook':
face.Profile(facebook, function(result) {
let like = result.profiles.like;
let comments = result.profiles.comments;
if(like === null || comments === null){
//code.
}
else {
//code.
}
});
break;
You have to verify that each child of your object exists before you reference the next level. In your case, that means testing the existence of result and then result.profiles before trying to use any of the object values in profiles. See the code below.
Without seeing the rest of your case statement or how you're setting the value of face, it's hard to tell if you're going to run into other issues.
case '!facebook':
face.Profile(facebook, function(result) {
// Set default values
let like = null;
let comments = null;
// Set values only if there's a result containing profiles
if (result && result.profiles) {
like = result.profiles.like;
comments = result.profiles.comments;
}
if (like === null || comments === null){
//code
} else {
//code
}
});
break;

jquery / javascript Load different content depending on session

hey guys i have this code here:
$('#internet').click(function(e){
e.preventDefault();
$.ajax({
url: "ajax/sessionset.php",
success: function (data){
if (data == 1){
$.ajax({
type: "POST",
//add variables
url: "ajax/loggedin.php",
success: function(data2){
//history.pushState({"internet.php?view=internetlog");
$('#internetlog').html(data2);
}
});
}
else if(data===0){
alert("suka");
}
}
});
});
The sessionset.php returns a value of either 1 or 0, depending if the session is currently going on or not.
Problem here is the link $('#internet')
returns the url loggedin.php when the data value is 1.
However if the data value is 0, nothing happens, since the e.preventDefault(); prevents any events.
Already checked on firebug that it either returns values of 1 or 0, I dont understand why the alert is not firing off when the value returned is 0...
edit: just checked the sessionset.php in a separate window instead of firebug
<?php
session_start();
if (!empty($_SESSION['origuserip'] && $_SESSION['loggedin'])){
$switch = "1";
}
else {
$switch = "0";
}
echo $switch;
the return value of 1 is 1 however if !empty is false it returns
Notice: Undefined index: origuserip in ajax\sessionset.php on line 4
0
SOLUTION:
Guess the simplest way is just the best way -_-
else {
("suka");
}
The scripts return value is probably a string, because you didn't specify the return type of your AJAX call.
You should validate like this: data==="1" and data==="0". Which checks for identity, as long as you definitely return strings.
data==1 is always true, if it's set and not null.
Regarding the other problem:
Make sure your $_SESSION variables are set properly when you check their indexes and separate the empty() checks. For example like this:
if (!empty($_SESSION['origuserip']) && !empty($_SESSION['loggedin'])){
$switch = "1";
}
else {
$switch = "0";
}
echo $switch;

IF-ELSE statement not working

I'm trying my best to create a website.
I need to create an IF-ELSE in ajax. It basically calls the content of an input called "greeting" and aims at writing "YES" if the user inserts a specific text and "NO" otherwise.
jQuery(document).ready(function () {
var greeting = jQuery("#greeting").val();
jQuery("#push-me").click(function () {
jQuery.ajax({
type: 'POST',
url: 'http://www.boatsandbeats.com/wordpress/wp-admin/admin-ajax.php',
data: {
action: 'myAjax',
greeting: jQuery("#greeting").val(),
},
success: function (data, textStatus, XMLHttpRequest) {
if (data == "XYZ") == 0 {
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
} else {
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
While the rest of the code works just fine, it does not recognize the IF and takes everything as if it were true (therefore, printing "YES").
Can anybody be so kind and explain this to me?
it is not working because your if statement is wrong
if (data == "XYZ") == 0 {
should be
if (data.greeting == "XYZ") {
}
Step 1: check if your ajax actually returns something.
...//add the following line
success: function (data, textStatus, XMLHttpRequest) {
console.log(data);
alert("Data logged." + data);
...
Step 2: what do you want to test?
You want to know if data (the ajax return) is a string and that string is having the value "XYZ"?
//change
if (data == "XYZ") == 0
//to
if (data === "XYZ")
Note the triple === it's not the same as ==. The difference is that === will check if the variables have the same value and the same type.
In addition, in Javascrip can compare string similar to your style like using localeCompare():
if (data.localeCompare("XYZ") === 0)
/* strA.localeCompare(strB); Returns:
0: exact match
-1: strA < strB
1: strB > strA
*/
UPDATE:
Assuming your php function is as the following:
function myAjax()
{
$greeting = $_POST['greeting'];
if (isset($_POST['greeting']))
$greeting = $_POST['greeting'];
$results = "<h2>".$greeting."</h2>";
die($results);
}
This is what's going to happen.
{
//$greeting is being assigned a value from POST greetings, // in post is empty then $greeting will be empty as well.
$greeting = $_POST['greeting'];
//You are validating POST greeting, although you already captured it's value and put it in $greeting, so why not using $greeting here instead?
if (isset($_POST['greeting']))// this if has no {} so ONLY the first line after will be included in this IF condition.
$greeting = $_POST['greeting'];
// this line will be exectue no matter what, so the value of $greeting will be entered into a string enclosed with <h2> tags. if POST greeting is empty, then $greeting will be empty of course.
$results = "<h2>" . $greeting . "</h2>";
//the variable $result now has "<h2></h2>" as it's value if $greeting is empty.
die($results); //echoing $result, or
}
So, since you have confirmed that you are receiving "" as a value for data variable returned from AJAX. Why are you comparing it to XYZ in your condition?
In your JS you are assigning "#greeting").val() to a variable greeting, then you use that variable as an array attribute for your ajax{data{greeting:jQuery("#greeting").val() }}
var greeting = jQuery("#greeting").val();// what is the use of this line?
Enclose your object attribute with "" e.g. "greeting".
data: {
"action": 'myAjax',
"greeting": jQuery("#greeting").val(),// what is the value of "#greeting").val()?
},
first of all you need to check data will exactly print XYZ or print [Object object]
if [Object object] then you need to check data.d=="XYZ"
in success function first parse then compare like this
var response=$.parseJSON(data);
if(response.field=="XYZ")
{
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
}
else
{
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
IF condition system is looks wrong,
if (data == "XYZ") == 0
You should use only, no need == 0
if (data == "XYZ"){
//.... code here
}
OR If ajax response in json
if (data.key == "XYZ"){
//.... code here
}

Why doesn't comparing var to "text" work?

I made an if and else statement in Javascript, but I can't get it to work.
This is my code, I hope you people will see whats wrong
var int = "";
function fbLoop (userLoop)
{
int=setInterval(function(){fbCheckloop(userLoop)},1000);
}
function fbCheckloop(userCheck)
{
if(userCheck.login != 'false')
{
window.clearInterval(int);
console.log(userCheck);
fbUpload(userCheck);
}
else
{
$.get("uploadtofb.php", {functie: "checklogin", fotonaam: userCheck.fotonaam}, fbCheckloop);
}
}
The if(userCheck.login != 'false') doesn't work.
The console.log(userCheck); shows this
{"login":"false","fotonaam":"NAME"}
So according to the console log he have to do the else, but he does the if statement.
What did I do wrong?
The userCheck is coming from this:
return json_encode($checklog = array(
'login' => 'false',
'fotonaam' => $_GET['fotonaam']
));
Are you sure that userCheck is a JavaScript object, and not a JSON string that has to be parsed? Your current console log result makes me suspect that it is. What does console.log(typeof userCheck) yield?
If it is, use
userCheck = JSON.parse(userCheck)
if userCheck.login is having boolean value false, use if(userCheck.login != false).
No quotes required around false.

Categories

Resources