how to handle null session in java script - javascript

Is there a way to get out of this error. I know it is null but i already put try catch in it why its still showing error and the condition if it is null but the error still showing that my session is null.
here's my code:
try {
if ('<%=Session["Selected"].ToString()%>' == null) {
loadTimesheetgrid();
}
else {
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs') {
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
}
catch (error) {
loadTimesheetgrid();
}
Error showing:
System.NullReferenceException: Object reference not set to an instance
of an object.

If your session value is null it will fail to convert it while .ToString()
So better you first check whether it is null or it has some value, if it has then only try to convert it into string.
if ('<%=Session["Selected"]%>' != null)
{
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs')
{
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
else {
loadTimesheetgrid();
}
I would suggest you not to place try and catch blocks in your view file as sometimes if it fails it loads partial html elements and you may face some alignment issues. However it is your choice to wrap your code in try and catch blocks.
try
{
if ('<%=Session["Selected"]%>' != null)
{
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs')
{
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
else {
loadTimesheetgrid();
}
}
catch(error)
{
loadTimesheetgrid();
}

I'm going to assume that you're using ASP.Net given your post history.
With regard to your question, there's two issues here. Firstly the Session["Selected"] is null on the server side so calling ToString() on that is the cause of your error. If you're using C#6 then you can use the null coalescing operator to return a string instead. If not, then you would need a separate if condition.
Secondly you need to compare the value to an empty string in your client side JS, as '' will never equal null.
Here's a full example:
try {
if ('<%= (Session["Selected"] ?? "").ToString() %>' === '') {
loadTimesheetgrid();
} else {
if ('<%= (Session["Selected"] ?? "").ToString() %>' === 'More Than 60 Hrs') {
//call the script you will make for morethan 60 hrs
} else {
loadTimesheetgrid();
}
}
} catch (error) {
loadTimesheetgrid();
}
Depdending on your use case you may want to consider providing the session value to the View using a ViewModel, to DRY this up a little.

Related

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.

How To Handle 'No Results Found' in a Search Feature

I am trying to display "No Results Found" in the case where someone uses my search feature to search for something that returns no results from the database. The problem I'm running into is that "No Results Found" prints to the screen right away - then disappear when a search query is actually being evaluated - and then reappears if no results were found. In other words, it's working as it should EXCEPT that it should wait till a query is actually triggered and evaluated before printing "No Results Found" to the screen. Conceptually what's the best way to do this? On the one hand it occurs to me that I could just use a timeout. But that's not really solving the problem directly. So what would be the best way to approach this? This is the code I have for the function:
public get noResultsFound(): boolean
{
if (this.query && !this._isSearching && !this.hasResults) {
return true;
}
}
Here's my view code:
<div *ngIf="inputHasFocus && noResultsFound" class="no-results-found">No Results Found</div>
Promises sound like what you need :D
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Something along the lines of this.
search = (paramObj) : Promise<SomeDataClass> => {
// Some search logic
}
requestSearch() {
this.search(null).then((result) => {
if (result.length === 0)
{
//logic for showing 0 results here
}
else{
// Show result?
}
})
}
A more complete example would look a bit like this.
class example {
public someBool = false;
public search = (paramObj): Promise<Array<string>> => {
this.someBool = !this.someBool;
return new Promise<Array<string>>((resolver) => {
// This just simulates something taking time.
setTimeout(() => {
if (this.someBool) {
resolver([]);
} else {
resolver(["hi","there"]);
}
}, 1000)
});
}
public requestSearch() {
this.search(null).then((result) => {
if (result.length === 0) {
console.log("empty")
}
else {
console.log(result)
}
})
}
}
So, in the end I was able to resolve this not by using some kind of debounce timeout, but by changing what the function was paying attention to - so to speak. By handling it this way the "No Results Found" never triggers before it's supposed to. This is what I ended up using:
public get noResultsFound(): boolean
{
if (!Object.isNullOrUndefined(this._results) && this._results.length < 1) {
return true;
}
}

How to check whether session is null or not in 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');
}

AngularJS check if promise is empty or not

Hi I have this code for the purpose of checking if there are users in the database, if it finds shows a list of users on a view, otherwise shows a view with form of user creation, but didn't work the check expression what I'm doing wrong
users = Users.query();
users.$promise.then(
function (data) {
if (!data) {
$location.url('/NewUser')
} else {
$location.url('/UsersList')
}
});
It is probably returning an empty array in case nothing is found. Try checking the data length.
if (data.length == 0) {
$location.url('/NewUser')
} else {
$location.url('/UsersList')
}

Javascript switch statement with wildcard?

If my javascript ajaxes away to my server and returns an ID of 49 in the plain text format of [49] is there a way in which i an do something like this... (i have tested and doesnt work)
switch(data)
{
case '[*]':
(..etc.)
break;
}
Where the wildcard is the * and i want to make sure it is enclosed within two square parenthesis?
Because i need to check that there wasnt another word returned like error and i am reserving the default for unexpected errors, any ideas? :) Thanks!
You can do a switch on true explicitely, which will use evaluation on each case statement.
switch (true) {
case ((/^\[\d+\]$/).test(data)):
//matches data;
break;
case (data == "something else"):
//...
break;
default:
//...
}
However, if you have less than say 4-5 cases, it would be better to use if/else if/else if/else blocks.
if ((/^\[\d+\]$/).test(data)) {
//matches data;
} else if (data == "something else") {
//...
} else {
//...
}
I usually do some error trapping in my response methods for service/rest calls so that I almost always return a proper json with an error property if there is an error.
try {
if (response.responseText.indexOf("<html") >= 0) {
throw response.responseText;
}
var data = JSON.parse(response.responseText);
if (data.error)
throw data.error;
//handle response data object.
if ((/^\[\d+\]$/).test(data)) {
//matches data;
} else if (data == "something else") {
//...
} else {
//...
}
} catch(err) {
if (err && err.message) {
//use err.message
} else if (err && err.toString().indexOf("<html") >= 0) {
//handle error text
}
}
You could create a list of patterns and associated callbacks and do a simple loop and check for matches. For example:
var patterns = [];
function myCallback(){ document.write('myCallback!'); }
function myOtherCallback(){ document.write('myOtherCallback!'); }
function myLastCallback(){ document.write('You will never see me!'); }
patterns.push({'pattern':new RegExp(/\[.+\]/),'callback': myCallback});
patterns.push({'pattern':new RegExp(/.+/),'callback':myOtherCallback});
patterns.push({'pattern':new RegExp(/A-Z{3}/),'callback':myLastCallback});
var f = "[49]";
for(var i=0;i<patterns.length;i++){
if(patterns[i].pattern.test(f)){
patterns[i].callback();
}
}
Which outputs the following:
myCallback!myOtherCallback!
You could try to use if else and regex for matching wildcard patterns.
Assuming data = "[49]"; or any digits inside brackets.
if(/\[\d+\]/.test(data)){
//do something
}else{
//default
}
Short answer: No, switch/case can't handle wildcard.
You should probably do some preprocessing/sanity checking before entering the switch, or simply discard it completely since it's more appropriate for specific case scenarios rather than processing streamlined data. Regexp will serve you better here.

Categories

Resources