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

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.

Related

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;

boolean check is not working in NodeJS

I am developing the node js API and I a querying data by the URL
get_posts_default?pageId=ge4JqBn9F0srzHnVFHmh&asking_post=false&asking_responce=false&maxSort=-1&minSort=-1&limit=20
This is the function who is responsible for handling this request
public async get_poset_list(userDeta: hs_I_fb_en_user_auth_paylode,pageId:string,asking_post:boolean,asking_responce:boolean,maxSort:number,minSort:number,limit:number):Promise<hs_I_fb_en_post_return[]>{
try {
hs_d_w("Is asking post: - "+asking_post);
hs_d_w("Limit: - "+limit);
if(asking_post===true){
hs_d_w("Asking post true");
if(minSort<=-1 && maxSort<=-1){
hs_d_w("Asking post Defolt");
return this._postQueryes.get_only_poses(pageId,limit);
}else{
if(minSort>-1){
hs_d_w("Asking post MIn");
return this._postQueryes.get_only_poses_min(pageId,minSort,limit);
}
if(maxSort>-1){
hs_d_w("Asking post Max");
return this._postQueryes.get_only_poses_max(pageId,maxSort,limit);
}
hs_d_w("Asking post None");
return [];
}
}else{
if(minSort<=-1 && maxSort<=-1){
hs_d_w("Asking talk Defolt");
return this._postQueryes.get_only_talkes(pageId,limit);
}else{
if(minSort>-1){
hs_d_w("Asking talk min");
return this._postQueryes.get_only_talkes_min(pageId,minSort,limit);
}
if(maxSort>-1){
hs_d_w("Asking talk max");
return this._postQueryes.get_only_talkes_max(pageId,maxSort,limit);
}
hs_d_w("Asking talk none");
return [];
}
}
} catch (e) {
hs_d_w("get_poset_list : " + e);
return Promise.reject(e)
}
}
Now if I call set asking_post=false or asking_post=true it allways call the main else area of this function
return this._postQueryes.get_only_talkes(pageId,limit);
This one.
I don't understand why it's happening? Can anyone please help me on this?
When you get something from the req.query it will always return a String. So, make sure to convert it to boolean using
const variable = (variable == 'true')
// or
const variable = (variable === 'true')
On a side note, when a variable is boolean you don't have to check explicitly with ===. This will also work
if(foo) {
} else {
}
EDIT: as #Kamalakannan said Boolean('string') will not work. My apologies.
Query params are considered as strings. So if you check with ===, it will be falsy.
Do string comparison, like if ("true" === asking_post) or if ("false" === asking_post)
Boolean(asking_post) will always return true for string values
const t = Boolean("true");
const f = Boolean("false");
console.log("Value of 'true':", t);
console.log("Value of 'false':", f);
So don't use Boolean(asking_post).
You can simply convert it with JSON.parse.
const x = JSON.parse('true');
const y = JSON.parse('false');
It will return boolean values for both.
When you get any values from request you always get String type.
So you need to convert it into Boolean first. Or just check with String.
You can do this: (I personally preferred)
var isTrue = (asking_post == 'true');
But please be caution to use following method:
var isTrue = Boolean("false"); // return true
var isTrue = !!"false"; // return true
Any string which is not empty will give you true by using the above methods.

Javascript function always returns 0

I am writing a function which searches for a value in my IndexedDB and if it finds one, then it should return 1, else it should return 0. The problem is that it always returns 0 though the value exists in a database (variable arr is incremented, but 0 is returned as a result). The code is as follows:
searchAllValues: function(store, type)
{
var arr = 0;
AAA.initDb(function()
{
var obj = {};
AAA.aaaDb.transaction(store).objectStore(store).openCursor().onsuccess = function(store)
{
var storeresult = store.target.result;
if(storeresult.value.value == type ){
arr++;
}else{console.log('value NOT found');}
storeresult ? (obj[storeresult.key] = storeresult.value.value, storeresult["continue"]()) : callback(obj)
}
});if(arr!=0){return 1}else{return 0}
}
EDIT_1:
Ok, I have refactored the code as follows:
addInfo: function(store, type, info)
{
var arr = [];
P4S.p4sPushDb.transaction(store).objectStore(store).openCursor().onsuccess = function(store)
{
var storeresult = store.target.result;
console.log('value of storeresult==>'+storeresult.value.value);
if(storeresult.value.value == info)
{
arr.push(storeresult.value.values);return;//If it finds something it should stop here, no more search or anything to be done
}else
{
console.log('continuing..');
storeresult['continue']();
}
console.log('arr length==> '+arr.length);//If it finds nothing after the looping the whole DB, I want it to print this statement, only once (to send it to my DB actually but sending code is omitted for simplicity).
}
}
Instead I get console.log('arr length==>') statement executed 2 times, for every key in my object store (there are 2 of them actually). So it is doing the code when it finds nothing AND when it finds the value in the DB. Any ideas how to fix it?
Any ideas would be welcome, Thank You
Because by the time the line if(arr!=0){return 1}else{return 0} is executed the db transaction is not complete and value of arr is 0. Though never used indexedDb, but webSql do take some extra miliseconds to read from DB.
Try to put your return logic inside the onsuccess function where you incrementing the arr. You can simply test it by printing value of arr just before your return logic
You need to learn about how to write asynchronous javascript. There are several other indexedDB questions where there are explanations as to why this happens.
For example: Uncaught TypeError: Cannot read property 'transaction' of null with an indexeddb
function addInfo(store, type, info, next)
{
var arr = [];
P4S.p4sPushDb.transaction(store).objectStore(store).openCursor().onsuccess = function(store)
{
var storeresult = store.target.result;
console.log('value of storeresult==>'+storeresult.value.value);
if(storeresult.value.value == info)
{
arr.push(storeresult.value.values);
next(arr);//If it finds something it should stop here, no more search or anything to be done
}else
{
console.log('continuing..');
storeresult.continue();
}
console.log('arr length==> '+arr.length);//If it finds nothing after the looping the whole DB, I want it to print this statement, only once (to send it to my DB actually but sending code is omitted for simplicity).
}
}
Added an extra parameter called 'next' to your the addInfo function.
'next' param is the very last function called if the condition (storeresult.value.value == info) is true.
The next function which you create, will use the 'arr' variable and do whatever with it
your 'return statement' doesnt work the sameway with asynchronous functions, would highly advice you search up asynchronous functions to get a gist of how its different to regular functions
This is how you would call your newly edited function:
addInfo(store,type,info,function(arr){
//do something with arr
})
Note that you have a potential state which would break your code
what if the cursor reaches the end of its iterations and never meets that condition (storeresult.value.value == info). storeresult would be null, and the check for the condition (null.value.value == info) will throw an exception
correction:
function addInfo(store, type, info, next)
{
var arr = [];
P4S.p4sPushDb.transaction(store).objectStore(store).openCursor().onsuccess = function(store){
var storeresult = store.target.result;
if(storeresult){
if(storeresult.value.value == info){
arr.push(storeresult.value.values);
next(arr);
}else storeresult.continue();
}else next();
}
}
And when you call it you handle the scenario whereby arr == null
addInfo(store,type,info,function(arr){
if(arr){
//do something with arr
}else{
//do somethingelse when arr == null
}
})

Using || to coalesce first non null value

Here is a function:
function() {
// if on wordpress site decipher if English or Français by using url path
var lang = '';
var wp_path = document.location.pathname.match(/^\/(en|fr)\//)[0];
if (wp_path == "/en/") {
lang = "Français";}
else if (wp_path == "/fr/") {
lang = "English";
}
// if on ruby site decipher if English or Français by using querySelector on element
var ruby_lang = document.querySelector('.menu--primary a[href*="lang="]').textContent.trim();
// either lang or ruby_lang will be null, assign value to opp_language accordingly
var opp_language = lang || ruby_lang;
return opp_language;
}
In the Chrome JS console this works if I type it line by line:
E.g. on url http://www.example.com/en/
var lang = '';
var wp_path = document.location.pathname.match(/^\/(en|fr)\//)[0];
if (wp_path == "/en/") {
lang = "Français";} // yes NOT English, it's opposite
else if (wp_path == "/fr/") {
lang = "English";
}
Returns Français as expected.
Then, when I'm on a page without a url path containing either en or fr I know that the variable "ruby_lang" will return either English or Français. I have verified this second part of the function works in the console.
So the 3rd part is presumably the problem. My expectation is that at this point, either lang or ruby_lang are set to a truthy value. So:
// either lang or ruby_lang will be null, assign value to opp_language accordingly
var opp_language = lang || ruby_lang;
But instead, whenever I run this function opp_language is undefined.
Does the double bar || syntax behave in a different way than I understand?
If after this line var opp_language = lang || ruby_lang; your variable app_language is undefined this means that both lang and ruby_lang are evaluating to false. If all values in a "coalesce series" evaluate to false the expression will return the last value in the list.
If you go ahead and type in your console right now var a = b || c where b and c are undefined and then log a you will see that it is indeed undefined.
When an element is not found by document.querySelector() your ruby_language will be null or undefined, if you are getting undefined then it most probably is.
So basically make sure your variables are initialized and have default values that don't evaluate to false, I guess.
I got this working but I don't really understand it. I used try and catch which I have never used before. From what I understood, if the variables could not be set they would just be falsy no?
Anyway, this works:
function() {
// if on wordpress site decipher if English or Français by using url path
var lang = '';
try {
var wp_path = document.location.pathname.match(/^\/(en|fr)\//)[0];
if (wp_path == "/en/") {
lang = "Français";}
else if (wp_path == "/fr/") {
lang = "English";
}
} catch (e) {
lang = false;
}
// if on ruby site decipher if English or Français by using querySelector on element
try {
var ruby_lang = document.querySelector('.menu--primary a[href*="lang="]').textContent.trim();
}
catch (e) {
var ruby_lang = false;
}
// either lang or ruby_lang will be null, assign value to opp_language accordingly
var opp_language = lang || ruby_lang;
return opp_language;
}

What location.hash.match return if there is no hash?

please can you tell me what does location.hash.match return if there is no hash ?
My code :
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
test = getHashValue('test');
if (test == 'abc') {
//code WORKS
}
else if (test == 'sal') {
//code WORKS
}
else if (test == "") {
//code DOESNT WORKS
}
but It doesn't works
I forget to mentionned that my code 'getHashValue' return the value of the hash Exemple : #test=abc
sorry I forget to mentionned it
Why not just?
test = getHashValue('test');
if (test === undefined) {
//code
}
EDIT
The error was from a null return in the match() call. The following change will return an empty string if the match is "" or null.
function getHashValue(key) {
var match = location.hash .match(new RegExp(key + '=([^&]*)'));
return match ? match[1] : "";
}
If you run location.hash in your browser console on any website where you're not using a hash, you'll find that it returns the empty string "".
As such, a regex match on that will find 0 results, returning null, at which point, you try to access null[1]...
location.hash will be empty string and your function:
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
Will indeed return undefined. The problem is that you are checking "undefined" value incorrectly. Change your code to:
test = getHashValue('test');
if (typeof(test) === 'undefined') {
//code
}

Categories

Resources