Requesting OAuth2 Token With AJAX - javascript

I'm trying to use AJAX to request a token. This will only be used on localhost to make the request. I've got the code:
$.ajax({
url: "TOKEN URL HERE",
beforeSend: function(xhr) {
xhr.setRequestHeader("grant_type", "client_credentials");
xhr.setRequestHeader("client_id", "ENTER CLIENT ID");
xhr.setRequestHeader("client_secret", "ENTER CLIENT SECRET");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
},
dataType: "json",
//content-Type: "application/json",
type: "POST",
success: function(response) {
token = response.access_token;
expiresIn = response.expires_in;
},
error: function(errorThrown) {
alert(errorThrown.error);
}
});
However, it doesn't work. Is this the correct approach or have I got the parameters incorrect? (Or is OAuth2 token request just not possible with AJAX/JQuery/JS)

The answer of Piotr P wasn't working for me. The client I am getting the tokens from did not accept the client id and credentials when send as part of the data. I had to use basic authentication instead. This is the ajax call that worked for me.
$.ajax({
"type": "POST",
"url": "https://some.domain.com/oath/token",
"headers": {
"Accept": "application/json",
"Authorization": "Basic " + btoa(username + ":" + password)
},
"data": {
"grant_type": "client_credentials"
},
"success": function(response) {
token = response.access_token;
expiresIn = response.expires_in;
},
"error": function(errorThrown) {
alert(JSON.stringify(errorThrown.error()));
}
});

Are sure, that grant_type, client_id, client_secret should be passed by headers instead of payload?
Try to remove them from headers (left accept, content-type only), and then add "data" property with rest of params.
Something like that:
$.ajax({
url: "TOKEN URL HERE",
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
},
dataType: "json",
data: {
client_id: "ENTER CLIENT ID",
client_secret: "ENTER CLIENT SECRET",
grant_type: "client_credentials"
},
type: "POST",
success: function(response) {
token = response.access_token;
expiresIn = response.expires_in;
},
error: function(errorThrown) {
alert(errorThrown.error);
}
});

Related

Converting cURL to Ajax and getting back Error 400

I am trying to store specific urls into jsonbox. However, I have been getting Error 400.
The curl command from the documentation is as below:
curl -X POST 'https://jsonbox.io/demobox_6d9e326c183fde7b' \
-H 'content-type: application/json' \
-d '{"name": "Jon Snow", "age": 25}'
Below is my edited code, putting in the link for jsonbox and URL as the data.
function send_request(url) {
this.url = url;
$.ajax({
url: 'https://jsonbox.io/box_89ad34d6d995aeb9ebb4',
type: 'post',
data: JSON.stringify(this.url),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
})
}
What am I missing or doing wrong here?
The issue seems to be the payload. Not sure why are you sending the url with your POST request. Check this working snippet:
$(document).ready(function() {
var payload = {
"name": "Maria",
"age": 78
}
$.ajax({
url: 'https://jsonbox.io/demobox_6d9e326c183fde7b',
type: 'POST',
data: JSON.stringify(payload),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
},
error: function(){
console.log("Cannot get data");
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to add extra fields in request JSON sent to DialogFlow former Api.ai

I am trying to append extra information to the jsonrequest that is sent from my application to DialogFlow. I am aware of the possibility to send data calling an intent by triggering its event from Sending Parameters in a Query Request, and I am using that method already for other functionality.
Basically, I am trying to add a value with the userID, and I need to retrieve that value in DialogFlow. I am keepeing track of the session in php, so I am using phpto get ID value. I have tried to do the following in the ajaxrequest:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100"
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
And this one as well:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100",
parameters: {
userId: "100"
}
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
I need that value in the request to process some data in the back-end based on it. If anyone knows how to do it, or has suggestions for a better approach that would be much appreciated.
There are discussion posts related to this in the DialogFlow Forums, but there is still no resolution. The feature might not be available, or it is not documented Link 1, Link 2, Link 3.
I solved this issue with the help of #Svetlana from Dialogflow. The original post is Here, and here is an example from a JavaScript application with back-end in Node.js:
You would format your request like:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({originalRequest: {data: {exampleMessage: 'Test'}}, query: text, lang: 'en', sessionId: 'somerandomthing'}),
success: function (data) {
},
error: function () {
setResponse("Internal Server Error");
}
});
and you would access the value in the webhook with:
var exampleMessage = req.body.originalRequest.data.exampleMessage;
or
var exampleMessage = req.body.originalRequest.data['exampleMessage'];
Hope this helps.

POST data to google contact api

I want to create new contact in google contact with google api with javascript and jquery, i can retrieve contacts with this sample :
jQuery.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
"max-results=100&" +
"v=3.0",
headers: {
'Authorization': "Bearer xs55.CjDOA8lRTs8567657567vXXXX",
'Content-Type': 'application/json'
},
method: "GET",
dataType: 'jsonp',
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('error: ');
console.log(data);
console.log(data.status);
}
})
Now i want to POST data and create or update items in google document there is always error ! :(
For example in this code "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://XXX' is therefore not allowed access. The response had HTTP status code 405." error happened :
jQuery.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
"max-results=100&" +
"v=3.0",
headers: {
'Authorization': "Bearer xs55.CjDOA8lRTs8567657567vXXXX",
'Content-Type': 'application/json'
},
method: "POST",
data: {title: "vvvv", phonenumber: "3333"},
//dataType: 'jsonp',
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('error: ');
console.log(data);
console.log(data.status);
}
})
whitout jsonp option there is no way to work that this option used when want to GET something not POST it .
Can you try this:
data= {title: "vvvv", phonenumber: "3333"};
$.ajax({
type: "POST",
data :JSON.stringify(data),
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
//"max-results=100&" +
"v=3.0",
contentType: "application/json"
});

I can't get Basic Authentication to Pass

I have searched the forums here for a while and am still at a loss. I am doing Basic Authentication with a predefined username and password.
I know that the username and password are correct because I can directly log in.
I have tried passing a "header", "username", "password" and as you see below using "beforeSend".
$.ajax({
type: "GET",
url: "https://vcc-na10.8x8.com/api/stats/groups.xml",
datatype: "xml",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password)); },
error: function (){
alert('cant connect');
},
success: function (){
alert('connected');
}
});
I think you need to use the headers parameter to pass authentication. Try this:
$.ajax({
type: "GET",
url: "https://vcc-na10.8x8.com/api/stats/groups.xml",
datatype: "xml",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
error: function() {
alert('cant connect');
},
success: function() {
alert('connected');
}
});
Try sending the username and password directly in the ajax config.
$.ajax({
type: "GET",
username: username,
password: password,
...

" Google API message " : " This API does not support parsing form-encoded input. "

I have written the following javascript to create a tasklist in google:
postData = {'title':'Netsuite List'};
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
The response says:
{ "error":
{ "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." }
}
What could be the possible error ?
not working
contentType: 'application/json; charset=UTF-8',
try with this
var headers = { };
headers["Content-Type"] ="application/json ; charset=UTF-8";
//remove to parsing form-encoded input error
data:JSON.stringify( model),
//this use for remove to parse error
Example:
$.ajax({
type: 'Post',
url: postUrl,
headers: headers,
dataType: 'json',//not required in some case
data:JSON.stringify( model),
success: function (data, sts) {
alert('success');
},
error: function (err, sts) {
var msg;
}
});
You sent data like:
title=Netsuite%20List
But Google API waits for JSON:
{ "title": "Netsuite List" }
Try to provide JSON.stringify() output to the requestURL method:
postData = JSON.stringify({'title':'Netsuite List'}); // <-- Added JSON.stringify
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
Also, it's better to get around documentation or source of $$ object you use and check how it can support sending JSON data.
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
beforeSend: (xhr) => {
xhr.setRequestHeader("Content-Type", "application/json");
},
//...
or :
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
contentType: "application/json",
//...

Categories

Resources