Using the LinkedIn API, I want to get the share count for an URL.
https://www.linkedin.com/countserv/count/share?url=http://www.linkedin.com&format=json
But this gives me an error because of Same-Origin Policy.
I want to use JSONP to then get the data, but I am stuck there.
$.getJSON("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback", function(data) {
elem.find(".count").html(data.count);
});
I still get the Same-Origin Policy error and no data from data.count.
Can anyone help me out? Thanks!
Try
myCallback = function(data) {
// do stuff with `data`
};
var url = "https://www.linkedin.com/countserv/count/share?"
+ "url=https://www.linkedin.com&format=jsonp&callback=myCallback";
$.getScript(url);
See jQuery.getScript()
myCallback = function(data) {
$("body").append("<pre>" + JSON.stringify(data, null, 2) + "</pre>")
};
$.getScript("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Thanks everyone for your answers, but I solved it already myself.
This worked for me:
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
As of jQuery 1.5.1, this is the recommended way of structuring AJAX requests:
$.ajax({
dataType: "jsonp",
url: "http://www.linkedin.com/countserv/count/share",
data: {
callback: "?",
format: "jsonp",
url: "http://www.example.com/"
}
}).done(function(data) {
console.log(data.count);
});
A few days ago, LinkedIn changed their API and the solutions above are broken :
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
fails because jQuery will replace the ? into a callback with a random name with numbers in it. And Linkedin now prevents using numbers in callback names.
The solution is to use to call "manually" $.ajax to prevent jQuery automation
$.ajax({
dataType: "jsonp",
url: 'https://www.linkedin.com/countserv/count/share',
data: {'url':encodeURIComponent(location.href)},
jsonpCallback: 'this_is_a_random_name',
success: function(data){
elem.find(".count").html(data.count);;
}
});
Related
is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}
I'm trying to replicate the WhateverOrigin service, seen here:
http://stackshare-importer.herokuapp.com/get_website?url=http://firebase.com
However when I try to run it on my browser this code which worked perfectly on WhateverOrigin no longer works with my dummy service:
$.getJSON("http://stackshare-importer.herokuapp.com/get_website?url=" + import_url + "&callback=?", function(data) {
console.log(data);
});
Uncaught SyntaxError: Unexpected token <
I just want to work with the html source string, how can I achieve this?
Edit:
Also tried this and get the same result:
$.ajax({
url: "http://stackshare-importer.herokuapp.com/get_website?url=" + import_url + "&callback=?",
jsonp: "callback",
dataType: 'jsonp',
success: function(response) {
console.log(data);
}
});
Sites like WhateverOrigin and AnyOrigin get the page you want and convert it to a JSON/JSONP object, which allows it to be used cross-origin.
If you are trying to replicate what those websites are doing, you will need to create a PHP script which gets the page as a variable and then converts it to JSON and outputs it in a JSONP object.
Change the PHP on your page "get_website" to:
<?php
$page = file_get_contents($_GET['url']);
echo 'jsonCallback({"html":'.json_encode($page, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT).'});';
?>
Then use this HTML/JS on any site to output the JSON:
<div class="stuffhere"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("document").ready(function () {
$.ajax({
type: 'GET',
url: 'http://stackshare-importer.herokuapp.com/get_website?url=http://firebase.com',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
alert(json.html);
$("div.stuffhere").html(json.html);
}
});
});
</script>
..and it will work!
I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});
I'm trying to call the google custom search API with JQuery and getting an access-control-origin error. This works:
<script>
function hndlr(response) {
console.log(response);
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
$('#content').append(item.htmlTitle + "<br/>");
}
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=AIzaSyABvGyx3nwDJJtbaRe2_UZhakVSpcxfebU&cx=017576662512468239146:omuauf_lfve&q=perlin+noise&callback=hndlr"></script>
but if I try to introduce jquery, it doesn't work:
var url = "https://www.googleapis.com/customsearch/v1?key=[MY_KEY]&q=perlin+noise&callback=hndlr";
$.ajax({
url: url,
dataType: 'json',
success: function(data){
console.log('data:' + data);
}
OR
$.get(url, function(data) {
console.log(data)
});
You are doing a cross domain request, so you have to use JSONP.
http://davidwalsh.name/jsonp
I recommend using $.getJSON
You would want to set the clear callback, so that that JSONP doesnt call a function
This seemed to work:
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp'
});
I am trying out JQuery Ajax methods. I wrote a simple Ajax request to fetch certain 'tagged' photos from Flickr. Following is the snippet I am using:
function startSearch() {
$(function() {
var tagValue = $("#tagInput").attr("value");
alert(tagValue);
$.ajax({
url: "http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tagValue + "&tagmode=any&format=json&jsoncallback",
dataType: 'json',
async: false,
success: function(data) {
alert("Success");
$.each(data.items, function(i, item) {
var pic = item.media.m;
$("<img/>").attr("src", pic).appendTo("#images");
});
},
error: function(data, error) {
alert("Error " + error);
}
}); });
'startSearch' is associated with a Search button. User is supposed to input a 'tag' to search and on click this function gets called.
Problem is that I am not receiving any 'data' in response. Hence no images gets displayed.
What am I doing wrong here?
Thanks & Regards,
Keya
I think the problem is that you're trying to make a cross-site request, which doesn't work because of security concern. You could use JSONP instead, e.g. as described in http://www.viget.com/inspire/pulling-your-flickr-feed-with-jquery/
You can also try searching for "cross site ajax" on this site, there's plenty of discussion about it.