How to retrieve a json from JavaScript - 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.

Related

Cross domain jquery ajax (Jsonp): Uncaught SyntaxError: Unexpected token : (colon)

I've been trying to pull data from the steam api, and have had no luck because I always get the above error. Here is the code I am using:
var steamurl = "https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?key=[keyomitted]&account_id=38440257&Matches_Requested=10";
function populate_api(){
var json;
$.ajax({
'url': steamurl,
'dataType': "jsonp",
'success': function (data) {
alert('success');
json = data;
}
});
}
I omitted my API key.
I have looked at many other posts, and cannot figure out where the problem is. I have tried using Jsonp, regular json, I have also tried using "&callback=?" after steamurl, but to no avail.
The solution for this is to add a local proxy that your jQuery code will call. Your proxy will be server side code (PHP, Python, Ruby, etc) that forwards the query on to Valve and then returns it to your jQuery call. You will, however, have to use one of their supported formats (of which JSONP is not one).
A high level view of what you'll be doing:
Create PHP file that accepts the parameters jQuery will be passing. In this case, it looks like account ID and matches you want to receive. Do not pass the API key, this should be stored in the PHP file
In PHP, build your steamurl using the stored API key, and the two passed values
Issue a call to the Valve servers using this steamurl and retrieve the results.
Return this response to your ajax call
Your PHP will look something like this (and should include more error checking since I am just taking the $_GET values as gospel:
$matches = $_GET['matches'];
$acct = $_GET['accountid'];
$APIKEY = <YOURKEYHERE>;
$steamurl = "https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?key=$APIKEY&account_id=$acct&Matches_Requested=$matches&format=json";
$json_object= file_get_contents($steamurl);
header('Content-Type: application/json');
echo $json_object;
Now you can use jQuery to parse this JSON response.

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 to avoid values not to display with the url while using window.location.href to pass values from one page to other?

In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!

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.

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

Categories