-1

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="" />
EigenMan
  • 3
  • 3

1 Answers1

0

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"; 
}
famabenda
  • 80
  • 1
  • 13