Facebook graph - Ajax / JSON showing url 'shares' - javascript

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

Related

Accessing JSON parsed object

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.

Passing an array from a page template to another php file in theme folder in WordPress

I have a front-page.php template which lists the 5 latest posts along with some custom post types in between. When one clicks on the more button at the bottom it needs to ajax load more posts.
So I created a loop-home.php file according to this tutorial
I couldn't use this code by default because I have a nested loop on the first load of homepage and this script messes it up.
So I wrote a new query to ajax OLDER posts only. I collected the post ids of the posts already present when the page loads and stored it in an array.
I now need to use this array in the query of loop-home.php
I am using this method because offset does not work with pagination and I need to pass these IDs to post__not_in parameter in the query.
Method 1:
I tried (in loop-home.php)
$exempt = $_REQUEST['exemptArray'];
But it returns NULL.
Method 2:(Using Ajax)
I tried (in front-page.php)-
<script>
var exemptArray = '<?php echo json_encode($exemptions); ?>';
</script>
Then I went to script.js and added-
//create json object from the var array
var jsonArray = JSON.stringify(exemptArray);
var dataToPost = { 'jsonArray':jsonArray };
//send POST data to PHP and handle response
$.ajax({
type: 'POST',
url: loopHome, //stored path in variable. working.
data: dataToPost,
success: function (data) {
console.log('I have already sent it.'); //I am getting this log. Working.
}
});
Then in loop-home.php-
$exempt = json_decode($_POST['jsonArray']);
Still getting NULL on var_dump($exempt)
What am I doing wrong?
Try this
You JS:
$.ajax({
type:'POST',
url:'foo.php',
data:{myArr:exemptArray},
dataType:'JSON',
success:function(result){
console.log(result);
},
error:function(data){
console.log(JSON.stringify(result));
}
});
Your php page:
$input=$_POST['myArr'];
$exempt=json_encode($input);
In your console you will get an array. [object object] is a reference to an associative array.So in the above code result is same as exemptArray.Try something like this you will be able to.I could not find your array composition anywhere so i used exemtarray itself.

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 data returned from Ajax appended to a div? -- JQuery + Rails 3.1

I'm trying to get data returned from a controller and append it to a div. Here is the code I have:
$(this).parent().find('list').append(__WHAT_GOES_HERE?__);
How should I get data to append using ajax in JQuery? I know this is a very basic question -- I'm new to JS :(
PS. Lets assume the controller's path is /ajax_get_items
I assume you want to load it into a class, so list would be .list
Something like:
$.ajax({
url: "/ajax_get_items",
type : "POST",
data : { // If you need data to be posted
id : 12,
num : "test"
},
success : function(result){
$(this).parent().find('.list').append(result);
// If a JSON object is returned, use the following line:
// $(this).parent().find('.list').append(result.html);
}
})
Or if you want to just load data without params (GET method):
$(this).parent().find('.list').load("/ajax_get_items");
If you want more information about ruby rails and jQuery: http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
This is what you need:
$.ajax({
url: '/ajax_get_items',
success: function(data) {
$('#selector').parent().find('list').append(data)
}
});
Note that you can't use 'this' in this context depending on where this call is made, or you might end up with unexpected results
$('somelink').click(function(e) {
e.preventDefault();
$.ajax(url, data, success:function(resData) {
resultSet = resData.extract(resData);
}
}
Basically this part handles the response from the ajax call and extract is supposed to build up your required html from the returned data.
After this you can simply say
$(this).parent().find('list').append(resultSet);
But this assumes the major work is done in the function extract with the returned data.
There you build up your list (or whatever) html is needed.

How do I get the counter of a google plus +1 button?

I have added a google +1 button to a website, but I want to get it's counter so i can do some math over it. is it possible to enter the iframe created by the standard method of creating the +1 button or do I need to make some adjustment?
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<g:plusone></g:plusone>
I've tried this link:1 , but this is not very accurate
If you can access curl/file_get_contents/readfile/wget or some way to fetch an external URL, this is quite simple.
Load the following URL: https://plusone.google.com/_/+1/fastbutton?url=URLENCODED_URI (UPDATED URL, see note below *)
URLENCODED_URI is the site you wish to know the number of +1's for, e.g. http://www.google.com (http%3A%2F%2Fwww.google.com)
For example, fetch the URI https://plusone.google.com/_/+1/fastbutton?url=http://www.google.com/ (UPDATED URI) and locate the first occurance of window.__SSR = {'c': 32414.0 ,'si'. Preferably use regexp for this, but I'll leave the implementation to you and your chosen programming language (server side or client side).
The float number following 'c' is the number of +1's the site have. For google.com this is 32,414. Don't worry about the float, you can safely convert it to an integer.
* UPDATE: The URL has been updated as the old URL started to 404. Remember, this is expected as this is an unofficial method. There exist no official method (yet).
Could you use a callback function to grab the value of the div that displays the count?
function count() {
var count = $('#aggregateCount').html();
}
<g:plusone callback="count()"></g:plusone>
I'm basing this off the bubble annotation button, I haven't tested it but something like this should work.
A pure client-side solution that works for me to get the Google Plus counter is as follows. It does not need an API key.
var url = "http://www.yoursite-to-be-counted.com";
var data = {
"method":"pos.plusones.get",
"id": url,
"params":{
"nolog":true,
"id": url,
"source":"widget",
"userId":"#viewer",
"groupId":"#self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
};
$.ajax({
type: "POST",
url: "https://clients6.google.com/rpc",
processData: true,
contentType: 'application/json',
data: JSON.stringify(data),
success: function(r){
setCount($(".google-plus-count"), r.result.metadata.globalCounts.count);
}
});
var setCount = function($item, count) {
if (count) {
$item.text(count);
}
};
Then I have some html with
<div class="google-plus-count"></div>
Credits here goes to this answer.

Categories