How to access Recurly API with AJAX? - javascript

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.

Related

NetSuite Restlet Using jQuery

I am trying to access a NetSuite restlet using jQuery. Here is my code for that:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
dataType: "json",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
When I check the "Network" tab in Chrome/FF it's giving me the following 401 response:
XMLHttpRequest cannot load https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.tracksandtires.com' is therefore not allowed access. The response had HTTP status code 401.
Am I not formatting the Authorization part correctly? I can't find any documentation on accessing a NetSuite Restlet via jQuery so I'm sort of shooting blind here. Should I just use vanilla javascript and not jQuery? Any help would be much appreciated!
Try using jsonp like this:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
crossDomain: true,
dataType: "jsonp",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
More info:
How does Access-Control-Allow-Origin header work?
Basically don't
Although #adolfo-garza 's answer does show JSONP correctly you gain nothing by using a Restlet and you give up a login that can never be used for something sensitive. Basically you've put one of your Netsuite credentials out on the public internet. Nothing good can come of this.
This is one of the use cases for Suitelets. You create a Suitelet that has public access (available without login; audience all roles) and then you don't need authentication (though there are ways to rely on shopping session or checkout session authentication if you need filtering information by customer).
If you are just trying to test a real Restlet Use Case then you should use Node or some non-browser based application to do that.

Correct use of JSONP

To successfully use JSONP (e.g. via jquery - $.ajax ... etc.) must always be that the requested page is designed to provide data corresponding to this format?
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also will I get an error?
This question might seem trivial to some users, but I'm starting right now to learn these technologies, and the matter is a bit complicated.
Based on these (ref1 ref2) references it would seem that there must be consistency between the request with JSONP and implementation of the server response.
Edit
I have this jQuery request
$.ajax({
url: "https://sites.google.com/site/problemsstore/javascript/test.js",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
And I have loaded in https://sites.google.com/site/mysite/javascript/test.js?attredirects=0&d=1 this test.js file:
function myCall(data) {
console.log('succeed');
}
myCall({ some : "data" });
When I am connected I hope to obtain as console's output: succeed succeed.
Instead this is what I get:
succeed
failed
Edit2
$.ajax({
url: "https://sites.google.com/site/bentofelicianolopez/jscript-jsonp/test.js?attredirects=0&d=1",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
jsonp: 'myCall',
//contentType: 'application/json',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
The .js file:
myCall({ some : "data" });
The output:
failed test4.html:94:9
ReferenceError: myCall is not defined /*this is the syntactical error of which I said*/
test.js:1:1
To successfully use JSONP (e.g. via jquery - $ .ajax ... etc.) must always be, that the requested page is designed to provide data corresponding to this format?
Yes. A request for JSONP will only work if the response is expressed as JSONP.
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also I will get an error?
You can have a static JavaScript program that conforms to the JSONP format (it requires hardcoding the callback function name), so not necessarily.

Setting headers in Twitter API POST

I am attempting to use the POST statuses/update Twitter API call. I'm new to this so please bear with me :). As outlined in this doc I've been trying to set up headers to use application only authentication.
What I have tried so far is as follows:
$(".tweet-later").on("click", function(event){
$.ajax({
url: "https://api.twitter.com/1.1/statuses/update.json",
data: { status: "Testing"},
type: "POST",
dataType: 'json',
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Rm5DVHpIc2M2ejRpeDRQRDRdfdsjprbjB5TENzeEZQNnhza2NFMzB6dnJMbnI2aENlRUZSczdOZUtWZUhaREhXSFVCY3dQWA==');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
},
success: function(data) { alert('Tweeted!'); },
error:function(exception){alert('Exeption:'+exception);}
});
});
I keep receiving an error: "Authentication Failed".All help is very much appreciated.
Thank you very much in advance.
What you're trying to do is impossible.
As it says in the documentation:
When issuing requests using application-only auth, there is no concept of a “current user.” Therefore, endpoints such as POST statuses / update will not function with application-only auth. See using OAuth for more information for issuing requests on behalf of a user.

Read RSS XML in javascript (cross domain)

I want to read rss(xml) file but without using google rss feed.
i have try jsonp but it download the file and it throw a error "Uncaught SyntaxError: Unexpected token < "
$.ajax({
type: "GET",
url:'https://news.google.com/?output=rss',
//url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: "xml",
contentType: "text/xml; charset=utf-8",
headers: { "Access-Control-Allow-Origin":"*",},
success: function(xml) {
alert("success");
}
});
plz guys help me..
$.getJSON("//ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?", {
num: 10,
q: url
}).done(function (data) {
console.log(data);
});
Notes:
You're overdoing it. Don't try to specify information on the client side that the server actually has to supply (content type, allow origin headers, data type).
You don't want XML, you want JSON.
The name for cross-origin JSON requests is JSONP.
jQuery implements that for you if you use the getJSON() API method. You don't have to do anything besides adding "callback=?" to the URL.
Use jQuery Deferred callbacks (then, done, fail and always). They allow your code to become a lot more flexible.
Have a look at the documentation, too. https://developers.google.com/feed/v1/jsondevguide
You basically can't implement a web client RSS reader because you can't be sure that content providers will set the correct CORS header for their feed(s) ; My advice would be to not waste your time reading through endless CORS/JSONP lectures (and trying misleading code) but implement a server solution (like, say Pétrolette) and move on.

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