Possible to get Asana tasks through JSON-P and Asana Connect? - javascript

Is it possible to connect to ASANA without a backend?
We have a secure folder on a webserver where we'd like to retrieve a task list of a project using only Javascript. Is that possible?
I saw some news from Asana that they support JSON-P through Asana Connect, but it's a bit unclear on how you could set this up from the documentation. Is there any examples available that I haven't found? Or have anyone succesfully set this up earlier?

The preferred way to do this is using CORS (added November 2013) - see this gist for an example of how you can use it. If you're unfamiliar with CORS, it stands for Cross-Origin Resource Sharing, and allows you to make cross-domain requests, given that the headers of the client and server match appropriately.

Incase anyone is already using Jquery (like I am) you can use the following code to do the same as the example from #agnoster.
$.ajax({
url : 'https://app.asana.com/api/1.0/users/me',
dataType : 'json',
type: 'GET',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(api_key + ":"));
}
}).done(function(response) {
console.log(response.data);
});
And if you need to POST/PUT you can use jQuery like this:
$.ajax({
url : https://app.asana.com/api/1.0/tasks/taskid',
dataType : 'json',
type: 'PUT',
data: { "completed": true },
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(api_key + ":"));
}
});
PS! you'll not be able to get this working for IE9 as it does not support sending headers (so the xhr.setRequestHeader() won't work)

Related

in Ajax, how to write "headers" for multiple condition?

as a beginner, I have some problems in using Ajax (with Discogs API) .. to get a discogs request token, discogs is saying
Include the following headers with your request:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
but, how to write this header?
below is my trying code, but I know this is not proper.
$.ajax({
type: "GET",
url: "https://api.discogs.com/oauth/request_token",
dataType: 'jsonp',
headers: {
ContentType: "application/x-www-form-urlencoded",
Authorization: OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback",
UserAgent: some_user_agent,
}
success: function (data) {
console.log(data);
document.getElementById("content").innerHTML += "<br>" + `${data}`;
},
error: function (error) {
console.log(error);
}
});
You said:
dataType: 'jsonp',
It isn't possible to specify headers for JSONP requests.
The API can't be using JSONP. Set the dataType to the format they are using.
The documentation says:
When you create a new application, you’ll be granted a Consumer Key and Consumer Secret, which you can plug into your application and start making authenticated requests. It’s important that you don’t disclose the Consumer Secret to anyone.
Putting those in your client-side code will disclose them to all your visitors.
The request to that end point should be made from server-side code.

Calling External API with Javascript

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?
This is what I have so far using jQuery and ajax:
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'json',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
It is throwing a alerts that just says "Status:" and "Error:"
The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."
Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.
If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).
Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN
You can use JQUERY and AjAX. You can send/get information information to/from your API either by post or get method.
It would be something like that:
$("#ButtonForm").click(function(){
$.ajax({
url:(Your url),
dataType:'json',
type: 'post',
data: yourForm.serialize(),
success:function(response){
** If yout API returns something, you're going to proccess the data here.
}
});
});
Ajax:
http://api.jquery.com/jquery.ajax/
You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.
Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.
My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.
When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.
Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'jsonp',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If you use jquery, use .post, or .ajax, to submit
$.post(url, data, callbackSuccess, callbackError);
more about these methods here http://api.jquery.com/jquery.ajax/
example:
var url = 'http://example.com/path/endpoint';
$.post(url, {name: 'Darlan', lastname: 'Mendonça'}, function(response){
// callback success
}, function(response) {
// callback error
});

Using CORS for Cross-Domain Ajax Requests. Test on httpbin.org doesn't work

I know that the issue already was discussed a lot. I went through the whole bunch of other SO's questions, but still has no solution.
My test case is very simple.
Requirements
I need to get authorised on httpbin.org site from my local server (localhost:63342). Basically I use http://httpbin.org/basic-auth/user/passwd to test HTTP Basic Auth.
I test Basic HTTP Authentication via jQuery.ajax function using GET request.
I need to get this done using exactly REST because actually my real goal is to get authorised via REST API request on teamcity's server which uses GET requests.
What I have done so far
Actually I tried enourmous things (worked with headers(Access-Control-Allow-Credentials, Access-Control-Allow-Origin), tried to use beforeSend function, dealt with jsonP, etc). No luck.
<html>
<head>
<script src="./jquery-1.11.0.js"></script>
</head>
<body>
<div id="target">
Click here
</div>
<script>
$("#target").click(function() {
var username = 'user';
var password = 'passwd';
$.ajax({
type: "GET",
beforeSend: function (xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
// I know, this one is redundant
xhrFields: { withCredentials: true },
crossDomain: true,
headers: { 'Access-Control-Allow-Credentials': true },
headers: { 'Access-Control-Allow-Origin': '*' },
// this one is redundant too
headers: { 'Authorization': "Basic " + btoa(username + ":" + password) },
//contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
url: "http://httpbin.org/basic-auth/user/passwd",
success: function(data, textStatus, jqXHR){
alert('success');
},
error: function(jqXHR, textStatus, errorThrown ) {
alert('failure');
},
// I don't know if I have to write it directly or not
username: 'user',
password: 'passwd'
});
});
</script>
</body>
</html>
Results I get
During all my tests I got different results. The code above causes httpbin to show auth popup window to type credentials (it's weird because I send user/pass pair in headers). Another results I've got were: UNAUTHORIZED status (which is quite understandable), "error" error message (which is meaninless), etc...
Experts of jQuery and cross-domain requesting, please help to figure out what should be done here.
P.S. I know this is highly related to CORS issue, but I tried to set Access-Control-Allow-Origin in different ways without any success.
Update:
Actually my initial goal is to be able to invoke CI job from JS code (TeamCity job via REST API using Basic HTTP AUthentication).
So, for TeamCity I believe there is a bug there (in REST API Plugin) - anyone who is interested in, please track the issue TeamCity's REST API Plugin doesn't allow to authenticate using Basic HTTP Authentication
Regarding httpbin.org - test is invalid at all.
Thanks a lot!

How to get Pingdom checks with JQuery .Ajax?

so far as I can tell my issue is that my GET request is not authorised. But my attempts to add authorisation in headers or as values in the URL (api key, username, password) are not being successful.
eg.
$.ajax({
type: 'get',
async: false,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
Can anyone advise as to correct Javascript syntax for interacting with the Pingdom API? I believe I'm trying to authorize incorrectly Their documentation focuses on PHP which I'm unable to use in this situation.
https://www.pingdom.com/services/api-documentation-rest/#authentication
I don't think it's possible to use the Pingdom API from Javascript in a web browser.
You'll need to use jsonp to get your browser to allow ajax requests across sites, but according to this response it's impossible to set headers in a jsonp request.
Use CORS Anywhere.
I wanted to get a simple jQuery request working that checked the last Pingdom result for our platform. Because of CORS and the need to specify custom headers for authentication, this didn't seem possible.
I didn't want to setup a proxy server for something so simple so I found this answer and was able to use the CORS Anywhere method, which looks something like this:
// Will use the cors-anywhere proxy if jQuery supports it and crossDomain option is passed in.
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
// options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
// Use ajax requests as normal.
$.ajax({
type: 'get',
async: false,
crossDomain: true,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
NOTE: Do not use this if you're passing or retrieving confidential information. You should use your own proxy if you're doing that. But if you're just getting public data, like we were, then this should be a nice and clean method to get around the CORS limitation.

Get OAuth request token through JSONP

I am trying to make a pure JavaScript Twitter application. I'm not concerned about the security involving the tokens since this is for internal use.
Currently, my code looks like this:
$.ajax({
url: 'https://api.twitter.com/oauth/request_token',
type: 'post',
data: {
oauth_callback: callbackurl
},
dataType: "jsonp",
headers: {
"oauth_nonce": nonce1,
"oauth_callback": callbackurl,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": Math.round(new Date().getTime()/1000),
"oauth_consumer_key": "IQKbtAYlXLripLGPWd0HUA",
"oauth_signature": "Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", //generate
"oauth_version": "1.0"
},
success: function(data)
{
console.info(data);
}
});
This code is rather incomplete, but the goal is to get what Twitter is returning (the request tokens). Obviously this code is not going to work because it violates cross origin policy. I have heard that this is possible with pure JavaScript, though. I need to send Twitter headers (at least, I think they have to be headers) then retrieve what they return.
Is there a workaround for this?

Categories

Resources