Accessing JSON parsed object - javascript

So here is my JS code:
$(document).ready(function() {
$.ajax({
url: "/",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success:function(data){
console.log(data);
},error:function(){
console.log("error!!!!");
}
});
});
And this is what I get in my console:
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
But now I'd like to do something like:
console.log(data.user_id)
But this return nothing..
Same for:
console.log(data['all_creations'].user_id)
console.log(data['all_creations'][0].user_id)
console.log(data[0].user_id)
...
I am using laravel5 btw and this JSON object is return by the toJson() function. (if this is any help)
I know this question has already been answered millions times but for some reason I cannot get it work on my project... I am not a pro in Javascript or anything related to it like JSON. Ajax, JSON remain for me a source of intense pain. I hope to get it one day... seriously ^^

If anything, this is a rough guide to how you can access your data:
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^ ^
The marked areas indicate that data is a standard object, so it has already been parsed.
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The inner portion says that data.all_creations is a property that contains a string value.
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The string value itself seems to contain a JSON encoded value, so you would need to parse that first:
var creations = JSON.parse(data.all_creations);
Then, from the string value you can see it contains an array with an object as the first element.
alert(creations[0].user_id) // 2

I feel like your best bet here would be to test it in Chrome and use the F12 developer tools to see what is coming back from the server. Maybe check the request in the Network tab or try to figure out the proper way to retrieve the user_id in the console.
If confused take a look at some F12 Chrome developer tools tutorials.

Related

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

Facebook graph - Ajax / JSON showing url 'shares'

I'm very new to using JSON and struggling to get to grips with retrieving data from an object and printing to HTML. The basic requirement is that i retrieve the url share count from facebook which aparently as its public data, i don't need to mess around with access tokens.
My script so far
$.ajax(
{
url: 'http://graph.facebook.com/?ids=http://google.co.uk',
success: function(json)
{
console.log(json);
}
});
Which returns the following as an object in the console.
[object Object] {
http://google.co.uk: [object Object] {
comments: 5,
id: "http://google.co.uk",
shares: 321364
}
}
So i can see the 'shares' data is there but how do i access it and print into a div? I've tried appending it to the 'sharecount' div like this
jQuery(response_container).append('<div id="sharecount">Shares: ' + shares + '</div>');
But i'm just fumbling in the dark and could use some guidance. Most guides on this seem to be out of date and recommend using the old FQL method.
I have a JSBIN here if anyone wants to take pity on me!
http://jsbin.com/qinutanotu/edit?html,console,output
thanks
UPDATE
I've now changed it to this which works
<script>
$.ajax(
{
url: 'http://graph.facebook.com/?ids=http://google.co.uk',
success: function(json)
{
var urlshares = (json['http://google.co.uk'].shares)
$("#sharecount").append(urlshares);
}
});
</script>
<div id="sharecount"></div>
UPDATE #2
graph.facebook.com seems to sometimes not return 'shares' and this might be to do with there being no shares for that url. Rather than returning '0' it returns nothing at all. To fix this i've replaced append with html and given the div a default value of 0 which gets replaced if the url has a share count passed back
<script>
$.ajax(
{
url: 'http://graph.facebook.com/?ids=http://google.co.uk',
success: function(json)
{
var urlshares = (json['http://google.co.uk'].shares)
$("#sharecount").html(urlshares);
}
});
</script>
<div id="sharecount">0</div>
Facebook uses the URL as key here, so you need json['http://google.co.uk'] first to access the inner object, and then json['http://google.co.uk'].shares to access the shares value.
(http://google.co.uk contains characters that make it impossible to use the dot notation to access the property using that key, therefor the ['http://google.co.uk'] has to be used here.)

How to access RESTlet SuiteScript parameters using GET method

I was stuck on a problem which probably plenty of new SuiteScript hackers will.
As writted on the official doc of SuiteScript p. 243, there's this JS for retrieve a record with GET method.
// Get a standard NetSuite record
function getRecord(datain) {
return nlapiLoadRecord(datain.recordtype, datain.id); // e.g recordtype="customer", id="769"
}
// http://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=22&deploy=1&recordtype=customer&id=769
But, when I was trying the EXACT snippet on NetSuite side, datain.recordtypewas undefined. (and return should only return text, BTW.)
Fortunately, I've found the solution by myself. Check my answer below.
In this snippet (the same as above) ...
function getRecord(datain) {
return nlapiLoadRecord(datain.recordtype, datain.id); // e.g recordtype="customer", id="769"
}
// http://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=22&deploy=1&recordtype=customer&id=769
—
SuiteScript was filling datain not as an object nor JSON but as a string (for reason I still ignore.)
What you have to do so is just parse it before, then access the JSON with dot notation.
function getRecord(datain) {
var data = JSON.parse(datain); // <- this
return "This record is a " + data.recordtype + " and the ID is " + data.id;
}
// http://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=22&deploy=1&recordtype=customer&id=769
I've changed the return statement in the solution because SuiteScript gives me error when I try to return something what isn't a text.
OR
As egrubaugh360 said, specify the Content-Type is application/json on your query script (the one who make call to your SuiteScript script)
So it'll give something like this if you're dealing with Node.js like me :
var options = {
headers: {
'Authorization': "<insert your NLAuth Authentification method here>",
"Content-Type" : "application/json" // <- this
}
}
https.request(options, function(results) {
// do something with results.
}
Hope this will help someone.

JQuery Unable to get property 'json' of undefined or null reference

Im building a windows 8 app (html)
And have a api im fetching data from.
I keep getting this error however
0x800a138f - JavaScript runtime error: Unable to get property 'json' of undefined or null reference
in my scripts1.js file. then my program crashes -_-.
Here is the the code i use
$(function () {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh, 10000);
var url = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132';
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json', function (data) {
jQuery('#ticker').html(data['query'].results.json.return.markets.DOGE.lasttradeprice);
jQuery('#ticker').append(' ' + data['query'].results.json.return.markets.DOGE.secondarycode);
jQuery('#ticker2').html(data['query'].results.json.return.markets.DOGE.lasttradetime);
jQuery('#ticker3').html(data['query'].results.json.return.markets.DOGE.volume);
});
}
This is located in scripts1.js Then i use ect.
It works everything comes and displays just get that error. Not sure what to do.
Seems like data['query'].results is undefined. Pasting the JSON you get will help.
Also, one small piece of advice: If you are going to access an in-depth attribute and, specially, a DOM node several times, you might want to recycle a reference to it rather than travelling again and again to fetch it for performance reasons. Something like this:
var ticker = jQuery('#ticker');
var DOGE = data['query'].results.json.return.markets.DOGE;
ticker.html(DOGE.lasttradeprice);
...
It looks like, occasionally, the API will send back some JSON that, when parsed, doesn't contain a results object. To mitigate this you should put a condition in to catch this eventuality.
if (data.query.results) {
jQuery('#ticker').html(data['query'].results.json.return.markets.DOGE.lasttradeprice);
// rest of DOM update code
}
Demo.

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