jQuery: using $.getJSON to get localization from aprs.fi - javascript

I want to use JSON to get localization coordinates from http://aprs.fi/page/api. I found example at http://api.jquery.com/jQuery.getJSON :
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "cat",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
</script>
When $.getJSON succed, it runs function(data), it puts 4 images on website. I paste this code in my html file and it works, so I changed it to get JSON data from aprs.fi:
<script>
$.getJSON("http://api.aprs.fi/api/get?name=OH7RDA&what=loc&apikey=_key_&format=json",
function(data)
{
alert("Anything");
});
};
</script>
Maybe my query is wrong, but even "Anything" doesn't print on my screen. I have no idea how to change it to make it works.

Just because a service can return JSON-formatted results does not mean that you can access it via JSONP. The site has to explicitly recognize such a request so that the response works as a JSONP response. (That is, the response must take the form of a function call, with the JSON return data passed as the argument to the function.)

The XHRs that getJSON is using are subject to same-origin-policy in web browsers; you can point XHR only to from only the exactly same server, port, protocol combination as the web page they are used in. If your web page runs on http://example.org:5625 it can only point XHR requests to http://example.org:5625/some-path-here.
The workaround is called JSONP where the resource is loaded as a tag. However, the service in question needs to be aware of it. You can tell if it is because after appending the callback parameter it should show something like
callbackname({"the": "respose", "goes": "here"});
that is, a function call to the named callback. However, if I understood correctly, the service you are using does not support JSONP. Then your only option is to make a serverside script that works as a proxy.

Related

How to get JSON Object from URL

I'm very new to web development.
When I input this link
https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412
into my browser, I can see the JSON object.
What do I need to do so can I use this JSON object in my javascript? I've tried using JQuery's $.getJSON with no luck.
EDIT
Using JSONP worked! Appending &jsonp=readJSON&?callback=? to the URL gave me back the JSON I wanted. Thank you for all the informative answers.
$.getJSON( "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412&jsonp=readJSON&?callback=?", function() {
console.log( "success" );
})
function readJSON(response){
console.log (response);
}
The question is, is this domain (api.locu.com) the same from where you serve your files? I suppose it isn't. In this case, you have two options:
Your backend can proxy the request from this site
You have to use a JSONP object if it's supported by the API
I'm no clear about your question, but I think you can use a call ajax, something like:
$.ajax({
url: "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412",
type: 'get',
cache: false,
success: function (response) {
console.log(response);
}
});
This should get the concept across if you are using JQuery... but you can use just about anything.
var url = "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412";
var result;
var settings = {
success: function(data){
result = data;
//do anything else related to this data here as you need it fetched, and is not linear.
}
}
$.ajax(url, settings);
Now, I noticed you used getJSON, which is pretty much the exact same. I did not however see you use a success function, so if you did your way, have you tried:
$.getJSON(url, function(data){
result = data;
});
I may be mistaken, but you say: "With no luck" so i have a limited understanding as to what you tried with $.getJSON
Not directly from inside a web browser, no. You would need to use a proxy: another server that makes this request in your behalf and then gives you the result.
Why not?
Web browsers are pretty tight on security. One of the strategies for protecting users from malicious activity is restricting the domains your Javascript can make HTTP requests to.
An HTTP request from your domain (the origin) to another domain is called a cross-origin request. These are forbidden by default, and you won't be able to read the response body, unless the received HTTP response includes the header Access-Control-Allow-Origin.
How then?
By using a proxy as an intermediary. The proxy is not a web browser, it doesn't care about Access-Control-Allow-Origin, and will read the response anyway.
There are a number of proxies you can use. An easy one is YQL (the Yahoo Query Language). Here's an article on the topic, using jQuery: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax

How to retrieve a json from JavaScript

I am trying to write a HTML5 mobile application and use jQuery to get a json from the url
http://cin.ufpe.br/~rvcam/favours.json I tried using
var url='http://cin.ufpe.br/~rvcam/favours.json';
$.getJSON(url, function(data, status)
{
console.log(data);
console.log(status);
});
but nothing shows up on the console. I don't see what I am doing wrong.
[EDIT] I learned from another post that I can't normally retrieve information from another server. But this server in particular (cin.ufpe.br/~rvcam) is mine. Can I use PHP or some other method to allow my application to retrieve the data?
The URL doesn't return valid json. It returns some JavaScript that attempts to execute a function called "foo" and passes the object as an argument. This is commonly called "jsonp". It is a method of achieving cross domain ajax calls
Your http://cin.ufpe.br/~rvcam/favours.json file isn't valid json. The valid json is wrapped in foo(). Remove the foo() from that file and it will work.

I dont get any data from the getJSON function

I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}
A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.
The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).
Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.

How do I create a JSONP from an external JSON feed?

I have two domains: www.domain1.com and www.domain2.com
I have a plain JSON feed on domain1.
I want to pull the JSON feed from domain1 and put it on a module on domain2.
From what I've read, the way to go about it is by using JSONP but how do you go about doing that? Is there a way to do it with just JQuery/javascript? Or would I have to use server-side code (I'm using Coldfusion). Also could I just use .getJSON and not .ajax (I'm a beginner so I've never used .ajax yet)
EDIT
Okay I'm still getting confused. Just adding callback at the end of the url broke it. How could I make it so that instead of a remote path for a feed I am pulling an absolute path where this code is on www.domain2.com but the feed is on www.domain1.com?
var feed ="/event/json.tag/tag/sports/";
$.getJSON(feed,function(data) {
$.each(data.items, function(i,obj) {
do something here...
}
}
JSONP is just a callback function wrapped around a JSON object.
General convention is to have an endpoint that returns JSON, unless a callback parameter is defined on the request, and returns JSONP in that case.
i.e. http://www.domain1.com/api/getStuff might return:
{'foo': 'bar', 'fizz': 'buzz'}
then http://www.domain1.com/api/getStuff?cb=cb123 should return:
cb123({'foo': 'bar', 'fizz': 'buzz'});
I don't know ColdFusion, but I assume this example is good: http://www.coldfusionjedi.com/index.cfm/2009/3/11/Writing-a-JSONP-service-in-ColdFusion
There's no client-only solution unless somebody else already built JSONP support into the server you're working with...
Reading the jQuery Documentation $.ajax and $.getJSON will be a good start, anyway there are a lot of good tutorials about jsonp, this one for example is a great tutorial:
$.getJSON("http://api.oscar.aol.com/presence/get?k=key&f=json&t=aimuser&c=?",
function(result){
if (result.response.data.users[0].state == 'online') {
$("#status").css("background-image", "url('online.jpg')");
}
}
);
As mention in the website:
The f parameter tells the service what
format to return the results in--JSON
in our case. The c parameter specifies
the JSON callback to use--this is
important!
And in the jQuery documentation:
If the URL includes the string
"callback=?" (or similar, as defined
by the server-side API), the request
is treated as JSONP instead.
So keep in mind sending a callback and handling the data afterwords will be easy.
EDIT: another good example.
EDIT2:
When not specifying the callback value, jQuery will assign it for you (from the $.getJSON page) the flickr URL will become:
http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=jsonp1294786450519&tags=cat&tagmode=any&format=json
And the response:
jsonp1294786450519({
"title": "Recent Uploads tagged cat",
"link": "http://www.flickr.com/photos/tags/cat/",
"description": "",
"modified": "2011-01-11T22:47:12Z",
"generator": "http://www.flickr.com/",
"items": [
{ .... rest of json
So you need to wrap your json with the callback sent from domain1
You could retrieve the JSON 'feed' from domain1 and pass that data as a parameter to your own Javascript function (on domain2) when your request is completed (onComplete / onSuccess).

Difference between $("#id").load and $.ajax?

Does anyone know what is the difference between $("#id").load and $.ajax?
Let me clarify things for you a little bit :
$.ajax() is the basic and low-level ajax function jQuery provides which means you can do what ever you want to like you can work with XmlHttpRequest object. But once upon a time jQuery Developers thought that actually besides $.ajax(), they could provide more specific methods to developers so they wouldn't need to pass more parameters to make $.ajax() method work the way they want. For example they said instead of passing json as a parameter to $.ajax() to indicate return data type, they provided $.getJSON() so we would all know that the return type we expected was json, or instead of indicating send method as post or get, you could use $.post() or $.get() respectively.
So load() is the same thing, it can help you inject html data into your html. with load() method you know that an html portion is being expected.
Isn't that cool ?
I think I've been fallen in love.
For more information, you can visit jquery.com, they are even providing their new library and api tutorial page.
Edit :
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
is the same as below :
$.post("some.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Now as you can see it is the simplified version of $.ajax(), to make post call, you need to pass some information of send method type which is post as shown at the first example but instead of doing this you can use $.post() because you know what you are doing is post so this version is more simplified and easy to work on.
But don't forget something. Except for load(), all other ajax methods return XHR (XmlHttpRequest instance) so you can treat them as if you were working with XmlHttpRequest, actually you are working with it tho :) and but load() returns jQuery which means :
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
in the example above, you can easly inject the return html into #objectID element. Isn't it cool ? If it wasn't returning jQuery, you should have been working with callback function where you probably get the result out of like data object and inject it manually into the html element you want. So it would be hassle but with $.load() method, it is really simplified in jQuery.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});
You can even post parameters, so according to those parameters you can do some work at server-side and send html portion back to the client and your cute jQuery code takes it and inject it into #feeds html element in the example right above.
load() initiates an Ajax request to retrieve HTML that, when returned, is set to the given selector.
All the jQuery Ajax functions are simply wrappers for $.ajax() so:
$("#id").load(...);
is probably equivalent to:
$.ajax({
url: "...",
dataType: "html",
success: function(data) {
$("#id").html(data);
}
});
A more concise summary and the most important difference is that $.ajax allows you to set content-type and datatype.
These two are important for making JSON requests, or XML requests. ASP.NET is more fussy with a missing content-type field (atleast when you use [WebMethod]) and will simply return the HTML of the page instead of JSON.
$.load() is intended to simply return straight HTML. $.ajax also gives you
caching
error handling
filtering of data
password
plus others.
From the documentation ...
$(selector).load(..)
Load HTML from a remote file and inject it into the DOM.
$.ajax(...)
Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation.
load is specifically for fetching (via GET unless parameters are provided, then POST is used) an HTML page and directly inserting it into the selected nodes (those selected by the $(selector) portion of $(selector).load(...).
$.ajax(...) is a more general method that allows you to make GET and POST requests, and does nothing specific with the response.
I encourage you to read the documentation.
Here's the source code for the load function: http://github.com/jquery/jquery/blob/master/src/ajax.js#L15
As you can see, it's a $ajax with some options handling. In other words, a convenience method.
The above answer may not be valid anymore in light of the use of deferred and promise objects. I believe that with .ajax you can use .when but you cannot do so with .load. In short, I believe that .ajax is more powerful than .load. For example:
some_promise = $.ajax({....});
.when(some_promise).done(function(){.... });
You get more granular control over the html loading. There is also .fail and .always for failure and "no matter what" cases. You don't get this in load. Hope I am correct on this.

Categories