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

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).

Related

Get jQuery $.ajax to send data in body for GET [duplicate]

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

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.

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

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.

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