Reputation: 37
I have used an api to get some information about someone who visits my page. The data is returned into a JSON format and I have used the .html function to set the content into some IDs like this:
$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
$("#lat").html(data.lat);
$("#lon").html(data.lon);
});
Using:
<p id="lat"></p>
<p id="lon"></p>
in my html body, I can see that the data has been set and is printed in my browser.
My question is how can I retrieve the data that is printed from the IDs into another, separate variable to continue to use/pass of to other functions ? I have tried using different functions like getElementById()
etc. but none have worked.
Upvotes: 0
Views: 2393
Reputation: 6664
You can use $(element).html()
to get contents of an element.
For example:
var someHtml = "<p>Hello world!</p>";
$(someElement).html(someHtml);
// This will set the html to be "<p>Hello world!</p>"
alert( $(someElement).html() );
// This will return "<p>Hello world!</p>" in the alert box!
To directly answer your question:
var coords = {
// lat coord
'lat' : $("#lat").html(),
// long coord
'lon' :$("#lon").html()
};
You can then reference them with coords.lat
and coords.lon
There's really no reason to set the coords
variable based on the HTML elements' values. Even if you have to display them, you'd be better off saving the variable directly from the API response to shave off some milliseconds.
So you might do this:
var coords = {};
$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
$("#lat").html(data.lat);
$("#lon").html(data.lon);
coords = { 'lat' : data.lat, 'lon' : data.lon };
});
As per your pastebin example - your error is coming from two places:
#map
div before it is renderedFirstly, move all your scripts to be below your HTML, so you will have <div id="map"></div>
right next to <table id="GeoResults"></table>
Lines 22-27 become:
<table id="GeoResults"></table>
<p id="lat"></p>
<p id="lon"></p>
<div id="map"></div>
latitude
before it is set.On lines 61 and 62 you try console.log()
and document.write()
to see the variable latitude
. It is not defined until immediately after:
console.log(latitude);
document.write(latitude);
var coords = {
// lat coord
'lat' : $("#lat").html(),
// long coord
'lon' :$("#lon").html()
};
So that obviously won't work - just move those lines until after you define latitude
and you're golden.
Upvotes: 3