-1

I'm trying to pull in the total shares from a number of pages and have them displayed on my home page. I'm using addthis for the share buttons. I found a way to pull in the required info using JSON here.

Since I have multiple urls I'm storing them in an array, then cycling through and calling each one. Here's my code...

jQuery(document).ready(function(){
    var shareCountArray = [ "url1",  //Array to put all url's to get share total
                     "url2"]  
    shareCountArray.forEach( function(shareUrl) { 
        var url = "//api-public.addthis.com/url/shares.json?url=http%3A%2F%2F"+ shareUrl +"?callback=?";
        jQuery.getJSON(url, function(json) {                                            
            alert(json.shares);
        }); 
    });
});

It's throwing up the error "Uncaught SyntaxError: Unexpected token : ". I thought this may have been because I included ?callback=? but when I remove that the console throws up errors because they're different origins.

Thanks for your time!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user1888521
  • 135
  • 1
  • 11

1 Answers1

1

When you include callback=? then jQuery thinks the response is JSONP. JSONP is nothing else than including a JavaScript file. I.e. the response you receive is interpreted as JavaScript. That also means that if the server returns anything else than valid JavaScript, you will get an error. JSON on its own is not valid JS syntax, that's why you get the that error (you can verify that easily by putting {"foo": 42} in the console).

when I remove that the console throws up errors because they're different origins.

JSONP as well as CORS have to be supported by the server. You can't make an Ajax or JSONP request to the server if it doesn't. See Ways to circumvent the same-origin policy for alternatives.

But it actually looks like the service does support JSONP:

When calling services that support html responses, you may omit the .html extension. Optionally, you can use json mode and pass callback=function to specify a jsonp callback wrapper. Content-Type headers are set on responses as appropriate.

Looking at your URL, it is malformed. You should use &callback=? instead of ?callback=?. Multiple request parameters in a URL are separated by &. ? only indicates the beginning of the query string. E.g.

http://example.com/?param1=value1&param2=value2

Learn more about URLs: https://en.wikipedia.org/wiki/Url

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143