How do you make an Ajax call to Google Drive API? - ajax

My code can get an auth2.0 token...but the examples I've found don't show the final piece of taking a GET, provided here, and turning it into a working request.
Here is the specific URL from that link:
GET https://www.googleapis.com/drive/v3/files/fileId
Here is my AJAX call with the attempt at getting the token (that works) into a hardcoded fileId that I know my Google account has access to.
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer" + token);
},
// url: "https://www.googleapis.com/drive/v2/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI/permissions",
url: "https://www.googleapis.com/drive/v3/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI",
dataType: 'application/json',
processData: true,
success: function(msg) {
console.log('Got File Metadata: ' + msg) + console.log(msg);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Error: ' + errorThrown + ' / ' + textStatus) + console.log(jqXHR);
}
});
I don't understand how to include the token and the pages and pages of Google documentation do not include any examples of going this route.
I get "invalid credential" errors in the server response.
I don't want to use GAPI because I ran into invalid cookie issues running locally and my code is in a Chrome Extension and it isn't clear whether that approach will work there.
Thank you for any help or direction.

In your code, this line:
request.setRequestHeader("Authorization", "Bearer" + token);
You should have a space after Bearer
request.setRequestHeader("Authorization", "Bearer " + token);

Related

Web Core API Post request get blocked, sometimes

I have this AJAX call to my Web Core API;
saveProperty = function (url, data, callback, errorCallback) {
$.ajax({
async: true,
type: "Post",
url: url,
data: data,
contentType: "application/json",
dataType: "text"
})
.done(callback)
//.fail(errorCallback);
.fail(function (jqXHR, textStatus, errorThrown) {
alert("Something went wrong: " + textStatus + " " + errorThrown);
errorCallback();
});
}
Sometimes it works, more often it does not.
When I use Fiddler and it works, I see
And when it doesn't I see;
EDIT - I can be more helpful now in describing this problem.
if I have Fiddler up and running before I lanch the aplication in development, I do not get this bug.
Otherwise I do get this bug.
Why is that? I would love to know.
The error is HTTP Error 401.2 - Unauthorized
Why would this happen with the same code?

How do I get Postman to call my Web API

I'm got the pluggin Postman for Chrome. I'm just wondering how I would get Postman to call my web API.
Current, I'm using this AJAX call written in Javascript:
alert("Getting security token");
// Do AJAX call to get security token:
$.ajax({
url: [security token url],
type: "POST",
headers: {
Accept: "application/json"
},
ContentType: "application/x-www-form-urlencoded",
data: {
grant_type: "password",
username: [username],
password: [password]
}
}).done(function(data)
{
var accessToken = data.access_token;
alert(accessToken);
alert("Getting json string.");
// Now that we have access token, send it along with the request for the json string:
$.ajax({
// meta data sent as URL parameters:
url: [url to get json string]
type: "GET",
headers: {
Authorization: "Bearer " + accessToken // access token
},
contentType: false,
processData: false
}).done(function(data)
{
$("#jsonDiv").html(data);
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
What would I have to do in Postman to accomplish the equivalent of this?
Thanks
There are a few ways to achieve this, but here are some steps to get you started. Create two 2 APIs:
The first to call the "security token url" with the POST method.
Add the header:
Accept: application/json
Then under body, select x-www-form-urlencoded and then add the following keys (and their appropriate values):
grant_type : password
username :
password :
Off the top of my head I think the password grant_type also requires client_id and client_secret, but I don't see that in your code above so maybe you don't need it.
If you hit send you should get an access token back.
In your second API, set the method to GET and supply the appropriate URL. Then in the headers add:
- Authorization : Bearer
If you want to get fancy you can use the test tab to write the access token to an environment variable and then use the result in your second call.
You don't need to get a new access token for each call however so you can just keep using the same token until it expires.
Sorry if you already knew how to do this, I couldn't tell your level of expertise from your question. Hope this helps.

Jquery Ajax request to Asana's oauth2 API

I'm developing an Asana app using Ember.js and I've running into some issue when I need to call the API. The oauth2 sign in/sign up is working great and I receive a working token ( tested it using curl)
I understand that I need to use the "Authorization: Bearer" header to auth with the API and this also work great using curl.
Here's my code:
$.ajax({
url: 'https://app.asana.com/api/1.0/users/me',
type: 'GET',
dataType: "json",
complete: function (resp) { console.log(resp) },
error: function (jqXHR, textStatus, errorThrown) { console.log( textStatus )},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization: Bearer", "my_access_token") }
});
When I execute this code, I get the following error
Uncaught SyntaxError: Unexpected token : me:1
parsererror
it looks like Asana doesn't reply with a properly encoded JSON file?
this the response that can't be parsed (sorry for the poorly formatted JSON)
{"data":{"id":864403617524,"name":"Sylvain","email":"my#email.com","photo":{"image_21x21":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_21x21.png","image_27x27":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_27x27.png","image_36x36":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_36x36.png","image_60x60":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_60x60.png","image_128x128":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_huge.jpeg"},"workspaces":[{"id":498346170860,"name":"Personal Projects"},{"id":3958612780941,"name":"insideFPL"},{"id":5502245946578,"name":"Shipping Pixel"}]}}
Any help is much appreciated.
Cheers,
S
The problem seems to be that you have set the Authorization header incorrectly. The following works for me:
$.ajax(
'https://app.asana.com/api/1.0/users/me',
{
type: 'GET',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token")
},
complete: function (resp) {
console.log(resp);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
}
);
Bearer should be at the beginning of the second parameter, and there should be no colon in either string.

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

Handling AJAX Origin errors, caused by the Chrome Extension

Is there way to handle AJAX Origin errors from Chrome's extensions ?
Denying load of
chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json.
Resources must be listed in the web_accessible_resources manifest key
in order to be loaded by pages outside the extension.
I tried this:
$.ajax({
url: 'chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json',
datatype: 'json',
success: function(xhr) {
alert('ok');
},
erro r: function(xhr, status, err) {
alert('status: ' + xhr.status + ' - ' + err);
}
});
but got nothing in variables. error status is "0", error message is empty.
You can try using the jsonp format. This often gets around cross-origin errors.
$.ajax({
url: 'chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json',
datatype: 'jsonp',
success: function(xhr) {
alert('ok');
},
erro r: function(xhr, status, err) {
alert('status: ' + xhr.status + ' - ' + err);
}
});
Sounds like you are attempting to load this resource from a content script, based on the error.
You have to explicitly add either the individual extension resources, or patterns that match your extension resources, in the manifest via web_accessible_resources. Your error message states this is the solution.
Once you've done this, you can construct the URL using chrome.extension.getURL(resourcePath).
Here's an excerpt from my manifest:
"web_accessible_resources" : [
"*.html"
]
And here's the code I'm using to request my HTML template file:
var url = chrome.extension.getURL("template.html");
$.get(url,function(data, textStatus, jqXHR){
console.log("Got the template!");
console.log(data);
},"html");

Resources