Amit Erandole Amit Erandole - 4 months ago 91
Ajax Question

Making a cross domain ajax request to a linkedIn api endpoint

I am trying to get the sharecount on a website's articles by making a

GET
request to a linkedIn api endpoint:

https://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json


This is my code:

$.ajax({
url: 'http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json',
type: 'GET',
processData: false,
crossDomain: true,
contentType: "application/json",
jsonp: false,
success: function(data) { alert('succeeded'); },
error: function() { alert('Failed!'); },
});


When I run it, I get:

XMLHttpRequest cannot load http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://aranca.craft.dev' is therefore not allowed access.`


What am I doing wrong? How do I access the sharedcount data?

Answer

You can just use dataType: 'jsonp' to resolve this CORS issue like:

$.ajax({
  url: 'https://www.linkedin.com/countserv/count/share?url=http://stylehatch.co',
  type: 'GET',
  contentType: "application/json",
  dataType: 'jsonp',
  success: function(data) {
    console.log('Count: ' + data.count);
  },
  error: function() {
    console.log('Failed!');
  },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

Comments