Unable to load JSON (Javascript) - 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

Related

How to examine the contents of data returned from an ajax call

I have an ajax call to a PHP module which returns some HTML. I want to examine this HTML and extract the data from some custom attributes before considering whether to upload the HTML into the DOM.
I can see the data from the network activity as well as via console.log. I want to extract the values for the data-pk attribute and test them before deciding whether to upload the HTML or just bypass it.
$.ajax({
url: "./modules/get_recent.php",
method: "POST",
data: {chat_id:chat_id, chat_name:chat_name, host_id:host_id, host_name:host_name}, // received as a $_POST array
success: function(data)
{
console.log(data);
},
})
and some of the console log data are:
class="the_pks" data-pk="11"
class="the_pks" data-pk="10"
etc.
In the above data I want to extract and 'have a look at' the numbers 11 and 10.
I just do not know how to extract these data-pk values from the returned data from the ajax call. Doing an each on class 'the_pks' does not work as at the time I am looking at the data they have not been loaded into the DOM.
I have searched SO for this but have not come up with an answer.
Any advice will be most appreciated.
I hope I understand your question.
If you get a HTML as a response, you can always create an element and insert that html inside it, without adding it to the DOM. And after that you can search it as you do with a DOM element.
const node = document.createElement("div");
//then you can do
node.appendChild(data);
// or
node.innerHTML = data;
And after that you can search inside the node:
node.querySelectorAll("[data-pk]")
I will re-engineer this - it was probably a clumsy way to try and achieve what I wanted anyway. Thanks to those who tried to help.

getJSON error - not sure where I'm going wrong

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.

Problems with displaying JSON data I got from a server

I'm new to JSON/AJAX and
I've some problems with displaying data out of a JSON-object I've got from a server..
The url "http://localhost:8387/rest/resourcestatus.json" represents this object, which I would like to display via HTML/Javascript.. This object stores some monitoring information:
{"groupStatus":[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]}
Since the requested url is different from my domain I can't create a typical XMLHttpRequest.. So I found out that there's an AJAX cross-domain request which can be realised via jQuerys "getJSON()" method.
I want to display the ids and their level in a table.
Any solution to achieve this?
i think you are referring to JSONP. see jQuery.ajax Ex:
var url = 'http://localhost:8387/rest/resourcestatus.json';
$.getJSON(url+'?callback=?', function(data)
{
//data is
/*{
"groupStatus":
[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]
}*/
});
on the server side you will need to wrap the response into a JavaScript function: response = Request["callback"] +"("+ response+")";
the result will look like this:
?({"groupStatus":[{"id":"AL ....})
So the browser will actually load a valid java script code.
The callback function of $.getJSON contains the result of the AJAX call in it's argument.
$.getJSON('http://localhost:8387/rest/resourcestatus.json', function(data) {
$(data.groupStatus).each(function() {
// do something with $(this).id
});
});

How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});

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