How to check whether session is null or not in javascript? - javascript

How to check whether session is null or not in javascript?It is right way?
if ('<%=Session["Time"] == null%>')
{
alert('null session');
}

Here's a solution that will test every 500 milliseconds if the user session has expired.
function CheckSession() {
var session = '<%=Session["username"] != null%>';
if (session == false) {
alert("Your Session has expired");
window.location = "login.aspx";
}
}
setInterval(CheckSession(),500);

You must try the following code:
var IsNull= '#Session["CallType"]'!= null;
Output:
IsNull value will be true or false.

I have used this code to check the Session.
public string TransactionID
{
get {
var data = ((Hashtable)(Session["SessionData"]));
if (data != null)
return data["TransactionID "];
else
return null;
}
}

if ('<%=Session["Time"] == null%>') will either evaluate to if ('True') or if ('False') which is equal to true in javascript: You may try as below:
if (<%=((Session["Time"] == null) ? 1 : 0))%>)
{
alert('null session');
}

Something like this should do it:
var isNullSession = <%=(Session["time"]==null).ToString().ToLower()%>;
if (isNullSession) {
alert('A null session variable I be');
}
This wouldn't mean the "Session" was null, just the session variable "time".
Steve

Here is the procedure to check whether session is null or not in Javascript. we have to do something like this.
var sessionValue = '<%=Session["Time"] != null%>';
So here is the point, if Session["Time"] is not null then it will return
'True' which is a string in this case. so then we can do our further
processing in this manner.
if (sessionValue == 'True')
{
alert('session is not null');
}
else
{
alert('session is null');
}

Related

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.

How to check if eval returns nothing in JS

If I want to check if an eval function returns nothing, how do I do it?
I tried to do something like:
if (eval("iwuoinuvwoienvuwope") == "") {
// Do something
alert("Oh NO!");
}
But when I do like that nothing happends.
Here is my full code:
function calc() {
var cal = prompt("Your math....", "1 + 1");
if (cal == null) {
alert("If you don't have a math problem you can gtfo!");
} else if (cal == false) {
alert("If you don't have a math problem you can gtfo!");
}
/* Here I Check if eval is empty */
/* Here it doesn't work */
else if (eval(cal) == "") {
alert("Could you be more specific");
}
/* */
else {
alert("The answer is " + eval(cal));
}
}
<button onclick="calc();">Calculator</button>
eval(code) returns "the completion value of evaluating the given code. If the completion value is empty, undefined is returned." MDN
In your case, a valid math expression returns a Number. Thus you would have to check for typeof result == "Number". If you want to exclude NaN, Infinity and the like, perform additional checks e.g. by isFinite(result).
If you are trying to build a calculator, you should either be expecting a response, an exception or null.
try {
if (r === undefined) {
} else {
// handle response
}
} catch (error) {
// invalid
}
Validating whether it's a Number, and if the mathematical formula is valid will help you identity possible error outputs.

true == false evaluates to true somehow?

I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.

check JavaScript variable null or not?

Iam using following lines of code to check whether the JS variable 'userName' is null or not.
But am always getting alert "not empty"
Please check my onready method:
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}
});
You need typeof keyword to check it's type. !userName will take care of the rest, like null or empty values.
if ( typeof userName === 'undefined' || !userName ) {
alert('empty');
}
You're setting var userName to "". It will never be null.
Declare your variable as var userName;, instead of var userName = "";
However, unless you actually do something with userName, the if / else will be pretty pointless.
No your variable is neither undefined nor null.
What you could do though is this replace this line
if (userName == undefined || userName == null) {
by this line
if (!userName) {
Empty string is not null nor undefined.
You can check using the ! operator:
if (!userName) {
// Do the stuff
}
For completeness:
!"" == true
!null == true
!undefined == true
!"hi" == false
Note that:
!0 == true
!1 == false
!"0" == false
!"1" == false
Try
var userName = "";
if (userName.length < 1) {
alert('empty' +"\n"+ userName.length);
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}

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