Google Feed API with jQuery`s AJAX - javascript

I'm trying to load a RSS feed using Google's Feed API which gives me a JSON string.
(documentation: https://developers.google.com/feed/).
However, I'm trying to use jQuery's AJAX instead of vanilla JavaScript XHR.
It is not working for some reason, which I can't identify why.
Loading the URL in the browser works, however (get the link in the code below).
I have prepared a jsFiddle: http://jsfiddle.net/gberger/fNwpD/
$.ajax({
url:'http://ajax.googleapis.com/ajax/services/feed/load?hl=ja&output=json-in-script&q=http%3A%2F%2Ffeeds.gawker.com%2Flifehacker%2Ffull&v=1.0&num=3',
success: function(data){
alert(JSON.stringify(data));
},
error: function(error){
alert(this.url);
alert(JSON.stringify(error));
}
});

Simply add dataType: 'jsonp' to your options object. Your code is not working because of the Same-origin policy. JSONP is one way of dealing with this if the server supports it (Feed API does).
$.ajax({
url: 'xy',
success: function () {},
error: function () {},
dataType: 'jsonp'
});
Your working fiddle

Related

How to access Recurly API with AJAX?

I'm using a jquery ajax call to a recurly API endpoint, but I get cross-origin errors. From my understanding, this is because Recurly only returns results as XML... when I use JSONP to get around cross-origin errors, I get an error because it receives the XML data but expects JSONP. Pretty obvious. But I'm trying to understand how exactly can one use this API at all via AJAX calls. I've been successfully able to access the API with PHP, but unfortunately, for this project, I can't use any client-side code.
Even if I find some sort of middle-code solution to get the XML and convert it to JSON for my side to accept, I need to utilize the API for POST requests (creating accounts, subscriptions, etc.) so I would like to understand how to utilize the API properly.
Here is an example of my code:
$.ajax({
url: "http://[DOMAIN].recurly.com/v2/accounts",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + window.btoa("[API KEY]"));
},
crossDomain: true,
type: "GET",
accepts: "application/xml",
dataType: "application/xml; charset=utf-8",
success: function (data) {
console.log("SUCCESS:", data);
},
error: function(e){
console.log("ERROR:", e);
}});
Anyone with Recurly API experience have any tips/advice?
From https://docs.recurly.com/api/recurlyjs/jsonp_endpoints
$.ajax({
dataType: 'jsonp',
url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}',
data: {
currency: 'USD',
},
success: function (data) {
// do stuff
},
}
You should not use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems.
Look at the JSONP endpoints that Byaxy linked to.

jQuery JSONP AJAX requests sometimes fail with "TypeError: Cannot call method 'done' of undefined"

I'm trying to use jQuery JSONP AJAX requests in a bookmarklet and I'm finding that the requests work on some pages, but not on others. Here's example code:
jQuery.ajax({
url: "http://echo.jsontest.com/key/value/one/two",
type: "GET",
dataType: "jsonp",
cache: false
}).done( function(data){
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("errorThrown: " + errorThrown);
});
If you go to the following Amazon page:
http://www.amazon.com/dp/B00336EUTK?psc=1
And execute the above code in your console, you'll find that it works. However, if you go to this Amazon page:
http://www.amazon.com/dp/B00E5UHSYW?psc=1
And execute the above code in your console, the following error appears:
TypeError: Cannot call method 'done' of undefined
What is causing this problem and how can it be fixed?
EDIT: One interesting thing I've noticed is that on pages where the AJAX requests works, the callback parameter always seems to look like this:
callback=jQuery1640586556919850409_1390439428297
On pages where it fails, it always seems to look like this:
callback=jsonp1390439502398
I've tried this on a bunch of different Amazon pages and it seems like that behavior is consistent.
Maybe it's just a coincidence, but I thought it might be worth pointing out.
Different versions of jQuery
Believe it or not, those two pages are using different versions of jQuery.
You can determine this yourself by typing this into the console: $().jquery
the first page is running v1.6.2
the second page is running v1.2.6
Looking at the jQuery docs for jQuery.ajax()(here), it looks like it was not added to jQuery until v1.5
Hope that helps.
If you run a console.log(jQuery.ajax); in console, you'll see that the second link you referenced does not contain a done function in the jQuery.ajax class (since they are two different versions). You can do a version check and handle two different solutions depending on whether or not jQuery has that class method. This works for both links you posted:
//get the jQuery version
var version = jQuery.fn.jquery,
parts = version.split('.');
//piece together a version integer
version = parseInt(parts[0]+parts[1]+parts[2],10);
if (version >= 150) {
//new method
jQuery.ajax({
url: "http://echo.jsontest.com/keyu/value/one/two",
type: "GET",
dataType: "jsonp",
cache: false
}).done( function(data){
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("errorThrown: " + errorThrown);
});
} else {
jQuery.ajax({
url: "http://echo.jsontest.com/keyu/value/one/two",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
},
error: function(e){
console.log(e);
}
});
}

jquery jsonp not working

$(document).ready(function() {
$.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?', function(data) {
console.log("success");
});
});
Why this code is not working? Its not giving error also in browser. But a project file is being downloaded as script in Chrome as shown by Inspect Element tool. How can I get data from the file?
It looks like Atlassian use jsonp-callback instead of callback as the parameter in a query string for JSONP callbacks.
See here.
I would suggest you configure your JSONP-call with the jQuery.ajax API like:
$(function() {
$.ajax({
type: "GET",
url: "https://jira.atlassian.com/rest/api/latest/project",
dataType: "jsonp",
jsonp: "jsonp-callback",
data: { /* additional parameters go here */ }
}).done(function(data) {
console.log("success");
});
});
The option jsonp renames the JSONP-callback parameter as #mccannf suggested from the API.
Also, for future reference, you might consider using the jqXHR object to add error-handling functionality, so you can tell if the JSON request is failing. See jQuery's reference (http://api.jquery.com/jQuery.getJSON/)
$(document).ready(function() {
var jq = $.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?',
function(data) {
console.log("success");
})
.error(function() { console.log("error occurred"); });
});

Retrieving user_timeline from Twitter in XML

I'm writing a simple app in HTML and Javascript. I'm trying to retrieve my user_timeline via jQuery's .ajax() method. The problem is that I want to retrieve my timeline in XML but I'm keep failing with this simple task. Here's my code:
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=stepanheller',
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
},
error: function(req, textStatus, error) {
console.log('error: '+textStatus);
}
});
Weird thing is that when I try exactly the same thing but with JSON instead of XML then the script works.
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=stepanheller',
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
},
error: function(req, textStatus, error) {
console.log('error: '+textStatus);
}
});
Can you give me some hints what I'm doing wrong with the request? I know that I'm using old version of API but I won't deal with OAuth right now. Thanks.
It is generally impossible to send a Cross-domain ajax request. It's the general rule.
JsonP is the classic way to work around this limitation, and there is no equivalent for Xml according to my knowledge. Depending on your browser compatibility constraints, you can use XHR2 to achieve this.
Otherwise, the only solution is to set up a server proxy.
Client --Ajax--> Your server --HttpRequest--> Twitter

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

Categories