I am trying to pull in information from Asana API via JQuery.ajax() method. But no desired result is returned, or error showed.
Here is my partial code in JavaScript:
$(document).ready(function () {
$('#buttonCallAjax').click(function () {
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: "https://app.asana.com/api/1.0/users/me",
data: "{}",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "jsonp",
success: function (data) {
alert(data);
},
error: function (msg, url, line) {
alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
});
});
I have read a lot about ajax() method, but still figured out some options parameters in this method, like data, dataType(because this is cross-domain request, I used jsonp).
Can someone please help with successfully pulling in information from Asana API?
Even though it looks as though the Asana API currently doesnt support JSONP, if in the future they do and you need to do authentication you can do it with the below code.
$.ajax( {
url : 'https://app.asana.com/api/1.0/users/me',
dataType : 'jsonp',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(API_KEY + ":"));
}
);
The btoa
function encodes to base64 but its not supported on all browsers so you may need to use some other library, if you need to support older browsers.
Update
The username name can also be set directly with jQuery no encoding or setting headers.
$.ajax( {
url : 'https://app.asana.com/api/1.0/users/me',
dataType : 'jsonp',
username : API_KEY
});
When using JS to access the API your API_KEY is going to be there on the page in clear text.Maybe this stuff should be done on the server side.