Problem with string: "undefined", unable to check this case [duplicate] - javascript

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm getting coordinates via an API that works most of the time
(giving me a String with a double, example : "53.2") but sometimes i see in the javascript console that I receive 'undefined' instead of let's say 53.2.
I tried to check if what i receive is undefined but it doesn't work and I keep getting this type of error sometimes:
"java.lang.NumberFormatException: For input string: "undefined" "
Could you help me please? I'd like to know if I have to check with another condition, maybe null or something else..
EDIT: My main concern is more to know when i get undefined value in the Java servlet and less to make the Javascript work better. Thank you!
//JAVA CODE IN THE SERVLET
String fromlong = request.getParameter("fromlong"); //COORDINATES
String fromlat = request.getParameter("fromlat");
String tolong = request.getParameter("tolong");
String tolat = request.getParameter("tolat");
if(fromlat == "undefined") {
fromlat = "50.0";
}
if(fromlong == "undefined") {
fromlong = "50.0";
}
if(tolat == "undefined") {
tolat = "50.0";
}
if(fromlat == "undefined") {
tolong = "50.0";
}
//Then there is a function that uses these values
and that's the javascript code where i get the values with an api then send them with a hidden input (this works when the api sends me a correct value most of the time then i'd like to check if what i got in the servlet is correct before using it)
getCoordinates1(from);
function getCoordinates1(database){
$.ajax({
url: 'http://api.positionstack.com/v1/forward',
data: {
access_key: 'MYKEY',
query: database,
limit: 1
}
}).done(function(data) {
var mylatitude = data.data[0].latitude;
var mylongitude = data.data[0].longitude;
document.getElementById('fromlat').value = mylatitude;
document.getElementById('fromlong').value = mylongitude;
console.log(data.data[0].latitude);
console.log(data.data[0].longitude);
});
}
and at the end of the page i send this with an hidden input
<input type="hidden" id="fromlat" name="fromlat" value="" />

You have to compare strings with .equals()
You are comparing them with "==".
If you do like you did, you are comparing the object reference, not the actual value of the string.
Which evaluates as false every time since it is not the same object.
if (fromLat.equals("undefined")) { ...
Edit:
You also have a logical error in your code:
if (fromlat == "undefined") {
tolong = "50.0";
}
should be:
if (tolong.equals("undefined")) {
tolong = "50.0";
}

Related

How to check empty in variable in Google Apps Script [duplicate]

This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Google Spreadheets Scripts: check if cell is empty
(3 answers)
Closed 1 year ago.
I have a variable that can be either empty, number or text. I like to find only empty one. But the following codes using .length returned null for 0 number, though it returned 1 for "0" string . .toString.length even didn't work. Any suggestion? Thank you!
function test() {
// criteria can be either empty, number or text. How can I check whether the critieria is empty?
// In the example below, critiera_2.length returned null, not 1.
criteria_1 = "";
Logger.log(criteria_1.length);
criteria_2 = 0;
Logger.log(criteria_2.length);
criteria_3 = "0";
Logger.log(criteria_3.length);
criteria_4 = "X";
Logger.log(criteria_4.length);
criteria_1 = "";
Logger.log(criteria_1.toString.length);
criteria_2 = 0;
Logger.log(criteria_2.toString.length);
criteria_3 = "0";
Logger.log(criteria_3.toString.length);
criteria_4 = "X";
Logger.log(criteria_4.toString.length);
}
criteria_1 = "";
console.log(criteria_1.toString() == ''); // output: true
const test = x => console.log(x.toString()==='');
test(""); // true
test(0); // false
test("0"); // false
test("X"); // false
It's turned out that you don't even need toString() it could be just x===''
To check for an empty string, a simple approach would be to use === operator
if (criteria_1 === "") {
//...
}

Json returns as undefined, replace undefined with text [duplicate]

This question already has answers here:
Javascript: use either a variable, or if it's undefined, a default string
(7 answers)
Closed 4 years ago.
first time dealing with json, so not really sure..
when a user online the api returns with
user example
live true
viewers 22
passwordProtected false
banned false
but when im offline "viewers" gets removed.
so data.viewers comes back as undefined, how can i change it to e.g offline?
script:
<script>
$.getJSON('https://example.com/api/example', function(data) {
var text = `${data.viewers}`
$(".mypanel").html(text);
});
</script>
You can use the hasOwnProperty function.
var text = "offline";
if(data.hasOwnProperty('viewers'){
text = data.viewers;
}
You could check for undefined like so:
var text = "offline";
if (data.length && data.viewers !== undefined) {
var text = data.viewers;
}
or with a ternary operator:
var text = (data.viewers !== undefined) ? data.viewers : "offline";
Ps. no need for the interpolation when saving a variable. ie `${data.viewers}`
This is used when adding variables to a string value like html.

Referencing a number in a JavaScript multidimensional object

The code I have below uses a number as a dataset in a JavaScript object:
spacenum = spacedetails[1];
//Create object for space number
if(spacenum in spaceobj['P1'] == false){
spaceobj['P1'][spacenum] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
}
spaceobj['P1'][spacenum]['Vacant'] = spacedetails[2];
spaceobj['P1'][spacenum]['Name'] = spacedetails[3];
spaceobj['P1'][spacenum]['Number'] = spacedetails[4];
spaceobj['P1'][spacenum]['Apartment'] = spacedetails[5];
This code goes around in a loop so 'spacenum' starts at 1 and goes up to the late 100s.
I am trying to access the data like so:
console.log(spaceobj.P1.11.Vacant);
However, the '11' is throwing up errors. I've tried brackets and quotes without any luck.
How can I access the data I want using a number?
In javascript '11' is not a valid variable name. However, because of its dynamic nature you can use:
console.log(spaceobj.P1["11"].Vacant);
Alternatively, one can also use:
console.log(spaceobj["P1"]["11"].Vacant);
Actually your line code below is undefined
spaceobj['P1']
Be sure your spaceobj['P1'] = false; has value
spacenum = 11;
spaceobj = [];
spaceobj['P1'] = false;
spaceobj['P1'][spacenum]= 'A';
spaceobj['P1'][spacenum]= 'B';

How can I set an if the query string is does come up as something other than

How can I make a javascript if function where if the query string does show as something other than undefined. Here is the code:
var getQueryString = window.location.href.split("?")[1];
alert(getQueryString);
Basically I wanted to do an if function in javascript. Here is the code:
if (getQueryString = 1){
//add code
}
How can I set my javascript function?
I would use location.search and check it's length instead of your approach.
if (window.location.search.slice(1).length > 0) {
doSomething();
}
Currently, your code will always execute because you're setting getQueryString to 1 instead of comparing it. Even if you were comparing it, it would still be false since getQueryString is a string and not a number.
The bellow code should work for you
var getQueryString = window.location.href.split("?")[1];
if (typeof getQueryString !== 'undefined')
{
//Your code goes here
} else [
alert("Query String not set");
}

How can I check if a referring domain is blank?

I've written a bit of JavaScript that reads the referring URL of a page and loops through an object to check for strings such as "google", "msn", "bing" etc. The resulting value is stored in a variable which is then passed to a server. Now this all works perfectly but my question is around detecting traffic directly to a site (i.e. people typing the URL in the address bar). How can I detect this?
I was thinking, that I could do something like:
var refURL = document.referrer;
var serverVar = "";
if (refURL === "") {
serverVar = 'direct traffic';
}
Should I be checking for "" (i.e. blank) or should I be checking if refURL is null?
If you dont want to do the way you are comparing now as in your code, You could use:
//check for blank, null or undefined
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
var refURL = document.referrer;
var serverVar = "";
if (isBlank(refURL)) {
serverVar = 'direct traffic';
}
Hope it helps
Just use if(!document.referrer) {}

Categories

Resources