getJSON error - not sure where I'm going wrong - javascript

With the help of a few other stack users I have come up with this:
http://jsfiddle.net/9ywLq/
I want to use an external json file & come up with something similar to this:
http://jsfiddle.net/RCB9M/
The file I am linking to at the moment is: http://www.lofiz.co.uk/afba/songkickwidget/testjsondata.json but this will ultimately change to a Songkick JSON output.

You are a victim of the same-origin policy. The browser will by default block JSON that is fetched cross-domain for security reasons. If you need to get data cross-domain, you will either have to implement a server-side proxy, or use JSONP, if the data is provided in that format as well. If the source doesn't provide data in JSONP, I believe you could utilize YQL to convert it.
Resource on JSONP: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/
Update: Your URL would be called like this:
​$(function(){
var url = "https://api.songkick.com/api/3.0/artists/253846/calendar.json?apikey=HlgKnFaq9qYO1h9T&jsoncallback=?";
$.getJSON(url, function(data){
// Do what you want to do with the return data within this callback
console.log(data);
});
});​
Update 2:
I have updated your JSFiddle to work with getJSON(). I also took the liberty to make a few other changes:
I modified how you defined your array of month-names, to make it more readable.
.getDay() in JavaScript is used to return the day of the week (0 = sunday, 1 = monday and so on), as I believe you want the day of the month, you should use .getDate() instead. See my JSFiddle.

Related

Is There anyone who knows what this piece of code does?

I am very new to javascript .. and my teacher provided us with this piece of code along with html and css file which on any date you enter gives you images of mars taken from ISS..
Would anyone care to explain what is happening inside the data: {} and how to get such API URL'S? I mean from where do we get that?
var input_box=$('#div-date input');
var button=$('#div-button button');
var container2=$('#container2');
button.click(function()
{
$.ajax({
method: "GET",
url: "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos",
data:
{
earth_date:parseInt(input_box.val().split('/')[2]).toString()+"-
"+parseInt(input_box.val().split('/')[1]).toString()+"-
"+parseInt(input_box.val().split('/')[0]).toString(),
api_key:"zrVafsMHD8r1SC8mHyg91mnNguuzdIoPRXGD1BvS"
},
The ajax method is a call to NASA endpoint where you are doing a GET call to the URL. I thinks this is clear.
Now, what does data?
earth_date is a value with the actual date parsed to a specific format. It get the date from the input_box with format 00/00/0000 and parse to format 0000-00-00
api_key is the key you need to authenticate and get the data.
And data itself is the way to send variables into URL. So, your url looks like this:
https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=YOUR_DATE&api_key=YOUR_API_KEY
Note that is compound by:
url+ ?earth_date + api_key.
Updated to answer the question:
The API key is a way to secure the API.
An API key is a way to identify who is calling the endpoint. So only calls that have the API key will be able to reach the endpoint (or whatever the developer want).
Is an string generated by the owner so the only way to get the API key is NASA to give it to you. I suppose NASA give free API keys, but is not a "general string" or something like that. Every organization will secure their apis in a way, NASA provide api keys to reach his 'free' endpoints.
The code in the data transform the date format '30/12/2019' to '2019-12-30' since only the later format is valid for the request.

Unable to load JSON (Javascript)

I'm trying to load a JSON file by link and then align data (like title, date etc) to variables so I can use them. Right now, I don't care about variables. I just want to alert() them but something seems like I'm doing it wrong, alert returns nothing!
I use JSfidle to run the code. The code is this:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json') ;
var JSON = JSON.parse(JSON_unparsed) ;
alert(JSON.feed.entry[0].title.$t) ;
The URL I want to parse is: http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json
and here you can see the JSON how is structured if that can help you:
You can use JSONP for this:
Update, for better understanding how to work with returned JSON.
var id, title;
$.ajax({
url: 'http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json',
jsonp: "callback",
dataType: "jsonp"
}).done(function(r){
// r is returned JSON
for(var i in r)
// for ex ID is this
id = r[i].id.$t;
// and title
title = r[i].title.$t;
// and so on, check the json, I mean check the browser console by hitting F12, below code will print the whole JSON
console.log(r[i]);
});
Codepen link: http://codepen.io/m-dehghani/pen/grXrrp?editors=0010
In addition to adeneo's reply, in your code, JSON_unparsed variable is holding something called (differed or promise object), this object might be holding the data inside it,but you are using the wrong way to pull it out. in order for you to get it out, you need to call (.done()) function, see the below:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json').done(function(json){
console.log(json);
console.log(json.feed.entry[0].title.$t);
});
aside from that, if you got an error with something like this:
XMLHttpRequest cannot load http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json&_=1459788714707. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.
it means that you are not allowed to call this API/URL from your current domain.
One more thing, if you are using getJSON method, there is no need to parse the returned data, jquery will parse it for you

load entire json file into variable as array

I want to take an external json file (locations.json) and load the contents into a variable. I would then like to use this variable using the information provided here: http://www.json.org/js.html
I've had a lot of trouble trying to load the external json to a variable. I've looked at this ( load json into variable ) page quite a bit, and none of that actually populates the variable. When displaying the variable's contents later, it appears to be empty.
$("#testContain").html("<p>" + json + "</p>");
Using methods listed in the last link, this dispays "undefined".
The json file that I am using looks like this:
[{"id":"1","locname":"Dunstable Downs","lat":"51.8646","lng":"-0.536957","address":"Chiltern Gateway Centre","address2":"","city":"","state":"England","postal":"","phone":"","web":"http:\/\/www.nationaltrust.org.uk\/main\/w-dunstabledownscountrysidecentrewhipsnadeestate","hours1":"","hours2":"","hours3":""},
{"id":"2","locname":"West Delta Park","lat":"45.5974","lng":"-122.688","address":"N Broadacre St and N Expo Rd, Portland","address2":"","city":"","state":"OR","postal":"","phone":"","web":"http:\/\/en.wikipedia.org\/wiki\/Delta_Park","hours1":"","hours2":"","hours3":""}]
Anyone have any suggestions?
The problem is that the request is asynchronous. You could make a synchronous call as suggested by the accepted answer to the question that you linked to, but that is generally not a good idea as it will freeze the browser completely while it is waiting for the response.
The variable is assigned just fine, but when you use it after requesting it, you have to make sure that it's after getting the response, not just after sending the request. Using the value in the callback for the getJSON method is the easiest way to make sure that you have the value:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
// here you have the value
});
// here you don't have the value, as this happens before the response arrives

Incorrect JSON data format

I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.

How to get JQuery to accept a JSON reply?

Here's some simple Javascript:
(function($){
var ajax_callback = function(data) { window.location.hash = data.h1; };
$('.clickable').live('click', function() {
$.post('server.fcgi', {}, ajax_callback, 'json');
}
);
})(jQuery);
The server is a c++ binary (yes, i know) that spits out (through fast_cgi) the string:
{"h1":"newhash"}.
The expected behavior is that the URL should change.
Instead, nothing happens and Firebug complains that 'data' is "null"!.
Any help would be greatly appreciated!
Will.
When the following code enters "ajax_callback", it says that "data" is "null"!.
But the server is a c++ binary that is confirmed to return the JSON string {"h1":"newhash"}.
Anyone have an idea why JQuery seems unable to accept the JSON data when calling the ajax_callback?
I did have similar problem as you have mentioned when using $.POST().
There are two things if you are using jquery $.post method. You need to add an extra bracket before defined data type ("JSON") as shown below. I don't know why but it works, it will return data.
$.post('server.fcgi', {}, ajax_callback,{}, 'json');
The second thing is that you will need to parse JSON data using $.parseJSON(data) in side the callback function.
One more thing to make sure that the url to fetch JSON, the page document type should be defined as JSON in the header.
I have given an example below.
$.post("url/path/here/to/json", {}, function(data){
if(data){ // just in case the called program had a problem
var obj = $.parseJSON(data);
.... do everything else using the Obj->
}
},{},"json");
This will work.
However I recommend to you to use another Jquery function specially implemented for JSON, that is called
$.getJSON();
Here is the url for more information
And I am suggesting you to use the following method instead of the one described by you.
$(document).ready(function(){
$('.clickable').live('click', function() {
$.getJSON('server.fcgi', function(data){
window.location.hash = data.h1;
});
}
);
});
Make sure the server also returns the correct HTTP headers before the payload. E.g.:
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: ...
...
{"h1":"bla"}
From your description, I could not quite make out if all it did was printf("{\"h1\":\"bla\"}"); or not.
To check the actual result, use a command line tool like HEAD, GET, wget, curl, or even nc. If you are not able to use one of those, you might get some clues from the Net panel in Firebug and the like.
Probably not the answer you want to hear, but I assume you're using jQuery 1.4.2? I noticed that this does work as expected in 1.3.2 so you might want to consider using that instead. :(

Categories