get the geolocation from IP , with "ipinfodb" - javascript

i know good javascript but totally novice in json and need to do the following:
get the geolocation from IP , with "ipinfodb"
like this response:
OK;;174.88.229.95;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
i found many codes for that but all seem to be complicate and long with more options like saving the results in cookies
i want the least necessary code to retrieve those informations
for saving them in cookies and more i want to care for it my self after.. (i don't like to put code i dont understand)
the best would be a simple function that returns this information as string or array, like this
function getLocFromIP(IP){
(js + json code)
return result;
}
much thank in advance
thank you all for responding i was trying to filter out the solution, and it works but i'm not yet well satisfied of the result..
i gonna reformulate my question here:
is there i can retrive the geo location from ip with simplest way (javascript) that means without json or jquery..
ajax would be perfect but it doesnt work inter domain (different domains)
thanks again
OK;;174.88.230.88;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00

The example you posted isn't valid JSON (you can check if something is valid JSON somewhere like here). That said, looking at the ipinfodb website they appear to have a way to get JSON output using their API (see here).
Once you have valid JSON, you can use JSON.parse. See here for some examples on using it.
So the general idea is
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON reponse)
//(js code using JSON.parse to parse the received JSON reponse)
//(js code to get whatever you want as the result)
return result;
}
As a side note, if you use jQuery you can also use jQuery.parseJSON to parse JSON (see here) which will be more reliable if you anticipate clients using older browsers that might not support JSON.parse.

IP location XML API requires some query strings like &format=json&callback=? additional to ip address in order to get json.
Then you get json like this:
{
"statusCode": "OK",
"statusMessage": "",
"ipAddress": "175.108.204.0",
"countryCode": "JP",
"countryName": "JAPAN",
"regionName": "TOKYO",
"cityName": "TOKYO",
"zipCode": "214-002",
"latitude": "35.6149",
"longitude": "139.581",
"timeZone": "+09:00"
}
Here is a sample code (thanks to #iveoak for good template):
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON response)
var url = 'http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=' + ip + '&format=json&callback=?';
var response = $.getJSON(url); // using jQuery
//(js code using JSON.parse to parse the received JSON response)
response.then(function (location) {
var info = '<ul>';
for (var key in location) {
info += '<li>' + key + ': ' + location[key] + '</li>';
}
info += '</ul>';
});
//(js code to get whatever you want as the result)
return result;
}
If you do not use jQuery, see How can I open a JSON file in JavaScript without jQuery?.
Sample (using jQuery): http://jsfiddle.net/tokkonoPapa/tevB4/

I post another answer.
This is a pure javascript solution using jsonp. Basically, it's a same concept using <script src="http://api.ipinfodb.com/..."></script>.
So you can accsess from anywhere, and do not need to handle json directly. You can simply get the javascript object.
Here is my demo: http://jsfiddle.net/tokkonoPapa/vCTpK/
UPDATE:
I/F is slightly different what you want. It uses a callback function.
getLocFromIP(ip, function(result) {
// use result
});
and the demo returns:
OK;;175.108.204.0;JP;JAPAN;TOKYO;TOKYO;214-002;35.6149;139.581;+09:00
I hope this basic solution satisfies you.

Related

Retrieving JSON data using the value of a variable

Hello. I'm currently working on a small project and have the following issue that I can't seem to solve alone. I have attempted to search for a solution, with no luck. Admittedly, it doesn't help that I'm fairly new at JavaScript/jQuery, so I'm unsure of the "correct" search terms!
I have a JSON file that contains the following code:
var draft = {
"title": "Title",
"subtitle": "Subtitle",
"image": "/image.jpeg",
}
I'm then retrieving the JSON data with the following line:
draft["title"];
Based upon what the application is required to achieve - is there a way to access the JSON data using the value of a variable in place of "draft"? I have an AJAX function that is pulling the file name and extension of the JSON file, and then the following line of code that is refining the file name down to one word by removing the slashes, numbers, hyphens, and file extension:
var fileNameRefined = fileName.replace("/", "").replace(/\d+|-/g, "").replace(".json", "");
As a result, the "fileNameRefined" variable will contain the value "draft". This outputs to the console as expected. That said, it won't work with the JSON. I was hoping that the following lines of code would work in the exact same way:
draft["title"];
fileNameRefined["title"]; // var fileNameRefined = draft
Unfortunately, the resulting data is returned as "undefined". I'm assuming the application is treating the name of the variable as a string as opposed to passing the variable's value? I'm not sure.
Does anybody have a solution to this? Any help would be greatly appreciated.
Thanks, all.
Could be done, SHOULDN'T be done.
Use JSON (This is JS object you presented) and its API. Here is example for jQuery, there are similar examples for other libs/frameworks.
I would always go with fw or lib here for a clear Ajax API over writing it yourself in vanilla.
Here is get JSON example in fiddle (not written by me):
json get fiddle
function getSuccessOutput() {
$.ajax({
url:'/echo/js/?js=hello%20world!',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
},
});
return false;
}
As for JSON api you will be interested in parsing the response using JSON.parse()
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Retrieving cross-domain JSON data, Javascript/JSON

I did some research on retrieving cross domain JSON data, but when I implemented it, the code didn't work. Doing some more research, I found that browsers don't let websites retrieve data from a different host due to security reasons. I found an answer that said I should use JSONP, but it still wasn't working? This was my code.
function getWeather(location){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=/*my usual app id is here*/&callback=?", function(result){
//response data are now in the result variable
alert(result.weather[0].description);
var changeW = document.getElementById("theweathertext");
changeW.innerHTML = "The current weather at your destination: " + result.weather[0].description +".";
});
}
When I test the code, the browser isn't letting me retrieve the data? How would I fix this? Thanks in advance.
UPDATE: This code was working when I was testing it locally, but when I did a live launch preview, it didn't work. Could this be some other problem?
I think this code will work if you provide a valid apikey:
$.getJSON(
'http://api.openweathermap.org/data/2.5/weather?q=lisbon&callback=?',
function(data){
console.log(data);
}
);
EDIT: It currently gives me 401 code which means i have no rights to access this endpoint. That is why i'm suggesting to use a valid api key.

Json object in jquery can't be read?

I am trying to read the finance info from the google page into a json object.
Code is below:
try {
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?",function(data){
alert(data);//var jsondata = data;
//jsonobj = $.parseJSON(jsondata);
//alert(jsonobj[0].id);
});
} catch(e) {
alert(e.toString());
}
However I keep getting this error all the time on firebug
invalid label
"id": "4052464"
Is there any way this info can be read. My ultimate goal is to create a windows 7 gadget that doesnt use server side scripting and can be used from any Windows 7 system.
Appreciate all the help.
John
Response isn't valid JSON (response is prefixed with //), so jQuery won't be able to parse it correctly anyway.
To solve change &jsoncallback=? to &callback=?
so
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&callback=?", function(data) {
alert(data)
});
The response from Google has two leading /'s, making the response invalid JSON... for some reason.
Because of this, you cannot use jQuery.getJSON, as it expects a JSON response. Instead, you should use jQuery.get, and parse the JSON yourself after removing the two leading slashes.
jQuery.get('http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?', function (string) {
var validJson = string.slice(2);
var obj = jQuery.parseJSON(validJSON);
// use obj
});
Two additional points:
No JSONP is being used, so you don't need the jsoncallback=? in your request URL
The Windows Sidebar has been retired, so you cannot publish you finished gadget to the official gallery.

How to extract JSON from URL?

I'm looking to extract JSON data from a server URL that looks something like this:
https://dev.randomdomain.com/subdomain
The URL itself outputs the data like such:
[
{ "name": "Not configured",
"mac_address": "####c##c####",
"online": "false",
"rate": "Not configured"},
{ "name": "Not configured",
"mac_address": "####c##c####",
"online": "false",
"rate": "Not configured"},
]
The outputed data changes and will need to be updated accordingly. I'm wondering what is the best method to retrieve the JSON data from the URL and keep it updated? I've looked at the jQuery getJSON function, and I'm not sure that will work as the URL is simply outputting JSON, it's not a .json file.
Can what I described be done using JavaScript, jQuery or any other open methodology?
Thanks.
$,getJSON('url',function(data){
alert(data);
// or alert("sample text"); would do if the json file is handled well enough.
// if no alert is shown, it's either you're using chrome with an offline version of
// your project or you're having an invalid json file
});
May I ask what browser are you using? $.getJSON won't work in Chrome if you are doing it in offline mode.
I also got frustrated why the json file not being processed even if I don't use Chrome - e.g. i use FF or IE.
I discovered that you shouldn't put comments inside the json file as it makes it invalid. I think, it's because .getJSON really parses data inside the JSON file as text, not as a javascript file, so it will also run through the comment (if you have any), and for sure won't understand it, so I suggest you remove comment block inside your json files.
Have you even tried using $.getJSON()? It does exactly what you need it to do, it simply reads the response from the server and returns a json object.
It is not very clear from your question if you want to process the data on client side (browser etc.) or on server side for offline processing.
For accessing and processing this data on server side, you can use curl/libcurl to pull data and decode it to an object in language of your choice. For example in php:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://dev.randomdomain.com/subdomain");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
data_as_php_object = json_decode($output);
?>
Firstly, you're actually trying to parse JSON from a response. The url is the thing you request a response from. Here is a simple example using getJSON:
$.getJSON('https://dev.randomdomain.com/subdomain', function(data) {
var output = "";
$.each(data, function(index, node) {
output += node.name + ": " + node.mac_address + "<br/>";
});
document.write(output);
});
http://jsfiddle.net/YwPzW/1/
The function $.getJSON() is to put the string in JSON format into a javascript object. So if you want to get the data, you can try as:
$.getJSON("https://dev.randomdomain.com/subdomain",function(data){
alert(data[0].name);
});
Do you trust the source of the JSON string. If you do, just use
alert(eval(dropStringHere));
The getJSON jQuery method should also work fine.

parsing json response

I'm calling a REST webservice and getting JSON format as a result. I'm calling rest service from another domain than mine. How can I parse this?
To answer the question you asked: There is a long list of parsers, including several for JavaScript, at the bottom of http://json.org/
If your question is actually: "How can I read JSON data from another domain with client side JavaScript in the browser?", then you can either fetch it using a proxy on the same domain as the page, or you can provide the data using JSON-P instead.
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
var myObject = JSON.parse(myJSONtext);
or use jQuery
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) {
alert(json.followers_count);
});
if you need only parsing jQuery also can do this:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
Are you getting the json result? Most implementations have protection agains cross site scripting and will only allow a request back to the original host of a page.
Could you please post some example code for your current implementation.

Categories

Resources