I followed this awesome tutorial to get the access and refresh tokens once the user logged in with their google account, but I always this response when I call GetAccessCode():
{
"error": "invalid_request"
}
Here's my code:
var url = window.location.href;
if (url.indexOf("code=") > 0) { //Once the user signed in with Google
var code_starts = url.indexOf("code=");
var code = url.substring((code_starts + 5), url.length);
alert("Code= " + code);
GetAccessTokens(code);
} else if (url.indexOf("access_token=") > 0) { //Get the tokens, but I never get this far
var at_starts = url.indexOf("access_token=");
var exp_starts = url.indexOf("expires_in=");
var access_token = url.substring((at_starts + 13), exp_starts);
alert("AT= " + access_token);
var rt_starts = url.indexOf("refresh_token=");
var id_starts = url.indexOf("id_token=");
var refresh_token = url.substring((rt_starts + 14), id_starts);
alert("RT= " + refresh_token);
} else {
GetAccessCode(); //If user opens the page, show him the consent screen
}
function GetAccessCode() {
window.location = 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https://mywebsite.com/quickstart.html' + '&response_type=code' + '&client_id=' + clientId + '&scope=' + scopes + '&approval_prompt=force' + '&access_type=offline';
}
function GetAccessTokens(code) {
window.location = 'https://accounts.google.com/o/oauth2/token?code=' + code + '&client_id=' + clientId + '&client_secret=' + clientSecret + '&redirect_uri=https://mywebsite.com/quickstart.html' + '&grant_type=authorization_code';
}
Here I receive the invalid_request error.
I tried to get the tokens via an ajax request to not have to redirect the page again (bad UX):
var red = 'https://mywebsite.com/quickstart.html';
var options = {
url: 'https://accounts.google.com/o/oauth2/token',
type: "POST",
dataType: "json",
data: "code=code&client_id=clientId&client_secret=clientSecret&redirect_uri=red&grant_type=authorization_code",
complete: function (e) {
alert(e);
alert(e.status);
},
};
$.ajax(options);
}
I tried it with headers, too:
headers: { "Content-type": "application/x-www-form-urlencoded"},
And I tried it this way, too:
$.ajax({
url: "https://accounts.google.com/o/oauth2/token",
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
alert(response); //I never get this
var json = $.parseJSON(response);
}
})
.fail(function(err) {
alert("error" + err); //I get [Object object]
});
And a few other stuff, too.
Oh, and all the parameters have the correct value.
Any ideas?
Ps: The oauth playground shows that the corrent token url is https://www.googleapis.com/oauth2/v4/token but when I use it I get Not found in the browser.
After 3 days I did it. Thanks for the console.log tip, #Brunt!
$.ajax({
url: 'https://www.googleapis.com/oauth2/v4/token',
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
console.log("Response: " + response);
console.log("AT: " + response['access_token']);
console.log("RT: " + response['refresh_token']);
access_token = response['access_token'];
refresh_token = response['refresh_token'];
}
})
.fail(function(err) {
alert("error" + err); //[Object object]
console.log("error" + err);
});
Related
This is the request that I am sending via javascript on a click of a button.
_crmProxy = "http://xxxxxxx:12355/dev_test/Service1.svc";
var name = "yz\\c.crm";
var pwd = "321#";
var text = "Parshu";
var response = null;
$.ajax({
async: true,
type: "POST",
headers : {
'Authorization' : 'Basic ' + btoa(name + ':' + pwd),
'Content-Type' :'application/json'
},
data: '{"userName": "' + text + '" }',
url: _crmProxy + "/WelcomeUser",
success: function (result) {
response = result.WelcomeUserResult;
},
error: function (error) {
alert("err");
}
});
but I am getting 401 Unauthorized OPTIONS error and couldn't go ahead. Can you please tell me where am I going wrong.
Thank you.
Prashant
I am trying to update a sp list with the following javascript/ajax. It succeeds until it gets to the ajax function, which is where it fails. It says the ItemID is not defined, when it is defined as:
var ItemId=item.ID
Any help appreciated.
<script type="text/javascript">
function updateMultipleListItems(){
var listName="Address Validation";
//CustomerNumber.val("16");
var CustomerNumber="CustNum";
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID&$filter=Cust_x0020_Number eq 17",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
alert("1");
var itemType = GetItemTypeForListName(listName);
alert("2");
var itemId = item.ID;
alert("3");
var item = {
"__metadata": {
"type": 'SP.Data.Address%20ValidationListItem'
},
"assign": "testinput"
};
alert("4");
$.ajax({
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
console.log('Update Success');
alert("Success");
},
// error: function(xhr, status, error) {
// var err = eval("(" + xhr.responseText + ")");
// alert(err.Message);
//}
});
}
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
What I'm trying to do:
I am trying to update all records in a list where the cust_number (a column in the list) field is 17 so that assign (another column) = "testinput".
eg:
Cust Number| Assign
17 | testinput
1 |
17 | testinput
I'm afraid you made a simple typo.
On a certain point in your code you declare the following:
var itemId = item.ID;
Later on you try to acces that same variable
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
However itemId != ItemId
Javascript is case sensitive.
I'm looking for a solution where I can provide URL to specific image and then with Javascript I retrieve data of that image. I alread found that I can't just pull file through, so maybe byte array or base64 will do?
To be specific before someone downvote that question: I want to parse URL and get image to my server in any form. There is a lot similar questions, but none of them answers this one.
What I need that for? I have access to API where I also am provided with image url's, but I want them to be uploaded to my server via Background Job in Parse.com service (something like CRON job). I know how to link file with ParseObject, but can't find solution how to download image directly to ParseCloud and link it.
var Image = require("parse-image");
Parse.Cloud.job("getImagesJob", function(request, status) {
Parse.Cloud.useMasterKey();
var beerObj = Parse.Object.extend("My_class");
var query = new Parse.Query(beerObj);
query.first().then(function(objs) {
var brew = objs.get("brewery");
var bname = objs.get("beer_name");
//var fullName = brew + " " + bname;
var fullName = "Browar Name";
console.log(fullName);
return Parse.Cloud.httpRequest({
method: 'GET',
url: 'api server address',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: {
q : fullName,
client_id : '...',
client_secret : '...'
}
}).then(function(httpResponse) {
var json = JSON.parse(httpResponse.text);
if(json.meta.code === 200){
if(json.response.beers.count > 0){
if(json.response.beers.items[0].beer.beer_label === "/default.png"){
console.log("brak etykiety dla " + fullName);
} else {
console.log("znaleziono etykietę dla " + fullName);
Parse.Cloud.httpRequest({ //NOT REACHING
url: json.response.beers.items[0].beer.beer_label,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
objs.set("logo", image.data());
console.log("udalo sie dolaczyc");
},
error: function(error) {
// The image data was invalid.
console.error(error);
}
})
},
error: function(error) {
// The networking request failed.
}
});
}
} else {
// daj cokolwiek żeby się nie zacięło na jednym
console.log("Brak danych dla piwa: " + fullName);
}
}
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status + httpResponse.text);
});
}).then(function(obj) {
status.success("Zrobione");
}, function(error) {
status.error(error);
});
});
You can use parse-image module in Cloud Code as in their documentation
var Image = require("parse-image");
Parse.Cloud.httpRequest({
url: YOUR_URL,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
console.log("Image is " + image.width() + "x" + image.height() + ".");
},
error: function(error) {
// The image data was invalid.
}
})
},
error: function(error) {
// The networking request failed.
}
});
With above code, you can get image data in Buffer using image.data(). To get base64 data, use image.data().toString("base64")
I have this functions
//send JSON-RPC request
var json_rpc = (function() {
var id = 1;
return function(url, method, params, success) {
if (typeOf(params) != 'array') {
params = [params];
}
var request = JSON.stringify({
'jsonrpc': '2.0',
'method': method,
'params': params,
'id': id++});
return $.ajax({
url: url,
data: request,
success: success,
error: function (XMLHttpRequest, textStatus, errorThrown) {
error_msg('XHR error ' + XMLHttpRequest.status + ' ' +
XMLHttpRequest.responseText);
},
beforeSend: function(xhr) {
console.log('before send');
console.log(dir(xhr));
xhr.onreadystatechange = function(){
console.log('state');
};
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
})();
var rpc = function(method, success_callback) {
//I use functional javascript library
var fun = json_rpc.partial('rpc.php', method, _, function(data) {
if (data['error']) {
var e = 'Json-RPC (' + method + ') ' + data['error']['code'] + ": " +
data['error']['message'];
error_msg(e);
} else {
info_msg("rpc sucess for method '" + method + "'");
success_callback(data['result']);
}
});
return function() {
fun(Array.slice(arguments));
};
};
and when I create function with rpc
var update_news = rpc('get_news', function(data) {
if (data) {
//update news
}
});
and call it
$(document).ready(function() {
...
update_news();
...
});
In Firefox everythig is fine, but in Opera and Chrome the function update_news is not executing, beforeSend is fired but onreadystatechange is not, but when I add
setTimeout(update_news, 0);
Then It's call normaly, also when I create synchronous call by putting async: false in $.ajax call or when I put timeout, timeout: 1. In click handlers it also run as expected.
$('#some_id').click(function() {
update_news();
});
Anybody know why this is happening.
When I use this code, I only manage to retrieve recaptcha_response_field. If I remove recaptcha_response_field, I retrieve recaptcha_challenge_field. However, I am unable to retrieve the two at the same time.
I only managed to send 1 data.
challengeField = $("#recaptcha_challenge_field").val();
responseField = $("#recaptcha_response_field").val();
var html = $.ajax(
{
global: false,
type: "POST",
async: false,
dataType: "html",
data: "recaptcha_response_field=" + responseField + "&recaptcha_challenge_field=" + challengeField,
url: "../ajax.recaptcha.php"
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
you wrote this line data: "recaptcha_response_field=" + responseField + "&recaptcha_challenge_field=" + challengeField, was wrong.
you can try this:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
or
data: {recaptcha_response_field : responseField , recaptcha_challenge_field :challengeField
thanks,
Chintu
Try
data: {
recaptcha_response_field: responseField,
recaptcha_challenge_field: challengeField
}
??
What do you mean that $_POST["recaptcha_response_field"] and $_POST["recaptcha_challenge_field"] are not both set "inside" ajax.recaptcha.php.
That's impossible Firebug's Net-Tab shows that the request just works fine.
Did you check your server logs (enable post data logging temporarily )
Maby something like this?
var challengeField = $("#recaptcha_challenge_field").val();
var responseField = $("#recaptcha_response_field").val();
/* Debug */ alert ("Going to send channengeField with value '" + challengeField + "', and responseField with '" + resonseField + "'");
$.post ("../ajax.recaptcha.php", {
recaptcha_response_field: responseField,
recaptcha_challenge_field: challengeField
},
function(data)
{
/* Debug */ alert ("Data Recieved: " + data);
if (data == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
});
You can try like this
data: "recaptcha_response_field=" + $("#recaptcha_challenge_field").val() + "&recaptcha_challenge_field=" + ("#recaptcha_response_field").val(),