-1

I need a function in JavaScript that can access an API to get the latitude coordinate for a particular IP address. The current function can print the latitude in the console when called. When I return the value, it is returned as undefined. I cannot get the function to return the value I have accessed from the API.

I have tried declaring the variable in numerous locations and have altered the function numerous times, but I cannot get the function to return or print anything but 'undefined' when outside of the internal function.

// Code for function 
function latitude(ip)
{
var latitudeData;

var access_key = '*******';

// Create a request variable and assign a new XMLHttpRequest object to it.

var request = new XMLHttpRequest();

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'http://api.ipstack.com/' + ip + '?access_key=' + access_key, true);

request.onload = function test () {
  // Begin accessing JSON data here

  latitudeData=data.latitude;
  console.log(latitudeData); // This will print required value. **
  return latitudeData;
  }
}

// Send request
request.send();

return test(); // get error from this line.
}

var ip = '134.201.250.155';

var p =latitude(ip);
console.log(p); // This will print undefined **
karel
  • 5,489
  • 46
  • 45
  • 50

1 Answers1

0

It's possible the rest of your code is already executing before the request comes back. You can try to make the code synchronous to pause its execution before receiving the request.

Example of a synchronous request from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}

If you don't want to do that just keep your code logic inside of your request.onload function.

Another option is to use an async function and await the return value.

Example: In JavaScript how do I/should I use async/await with XMLHttpRequest?

lloyd
  • 1,089
  • 1
  • 17
  • 39