Trigger.io Ajax Requests - with Parse Facebook User authentication - ajax

I'm trying to authenticate users from Trigger.io, ideally via Facebook.
I authenticate the user via Facebook (using the Parse Facebook module), and pass their access token, acess expiry date, and facebook Id to my call to Parse.
It is here things go wrong. Whenever I try and post this data via Ajax to the Parse REST API, I get an error in my forge/Trigger console reading:
{ type: 'EXPECTED_FAILURE', content: '{"code":107,"error":"This
endpoint only supports Content-Type: application/json requests, not
application/x-www-form-urlencoded."}', statusCode: '400', message:
'HTTP error code received from server: 400' }
The code I used to try and post this data is...
function auth(facebookId,accessToken,expirationDate) {
forge.logging.log('auth started');
forge.request.ajax({
url: 'https://api.parse.com/1/users',
headers: {
'X-Parse-Application-Id': config.parseAppId,
'X-Parse-REST-API-Key': config.parseRestKey,
'Content-Type': 'application/json'
},
type: 'POST',
dataType: 'json',
data: {
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
},
success: function (data) {
forge.logging.log('auth finished 1');
forge.logging.log(data);
},
error: function(error){
forge.logging.log('auth finished 2');
forge.logging.log(error);
}
})//success
} //auth
I can't figure out how to send this as a JSON object/ in the correct format. If anyone has any ideas they'd be much appreciated. Thanks. Josh.

Whenever the data option passed to forge.requests.ajax is an object like in your example, what actually gets posted is a query string that represents the object. The contentType option merely allows you to set the Content-Type header, it does not effect how objects are encoded for the request.
However if the data option is just a string, then this string is used as the body of the request. You can generate a JSON string to use as the body using JSON.parse like so:
forge.request.ajax({
...
contentType: 'application/json',
data: JSON.stringify({
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
})
});

Related

What is the correct way of create a get request for retrieve a tickets in zendesk

if my username is name123#test.com and API token is 123456789 then how to create a get request for retrieving tickets related to the user
I tried this way and got always unauthorized as response
$.ajax({
url: 'https://mysubdomain.zendesk.com/api/v2/requests.json',
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Basic
name123#test.com;123456789");
request.setRequestHeader('Content-Type', 'application/json');
},
success: function (data) {
console.log( data);
},
error: function (err) {
console.log(err);
}
})
As per the documentation here, the proper format for using tokens is {email_address}/token:{api_token}, as in jdoe#example.com/token:6wiIBWbGkBMo1mRDMuVwkw1EPsNkeUj95PIz2akv. So looks like you need to add /token and the ; semicolon should be replaced with a : colon.

How i can send delete request for to delete video in AJAX, its returning 204 status

I'm trying to delete my vimeo video by using AJAX request but its always returning 204 status code, and video is not deleting from account. Here is code example.
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: "post",
url: "https://api.vimeo.com/me/videos",
headers: {
"Authorization": "bearer xxxxxxxxxxxxxxx"
},
data: {
url: "https://api.vimeo.com/me"+videoID,
method: "DELETE"
},
dataType: "json"
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
Can anyone please suggest some changes required for this?
Thanks in advance
You are sending
a HTTP POST
to the URL https://api.vimeo.com/me/videos
with the Bearer token as a header
Note that it should be Bearer <token> (uppercase B), not bearer <token>.
with a data packet that contains another URL and HTTP method.
But according to the Vimeo API docs to Delete a Video, the request should be
DELETE https://api.vimeo.com/videos/{video_id}
with a note:
This method requires a token with the "delete" scope.
A jQuery ajax request should look something like this if the bearer token is correct:
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: 'DELETE',
url: 'https://api.vimeo.com/videos/' + videoID,
headers: {
"Authorization": "Bearer xxxxxxxxxxxxxxx"
},
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
You should be able to test this request using https://www.getpostman.com/ to verify the request and bearer token works outside of your CF app.

Using fetch with method post

I have a phonegap application that uses
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: 'bob#test.com' }
)
which i get in my glassfish server doing something like
HttpServletRequest request;
request.getParameter('mail');
I'm moving my application in react native so i'm doing
fetch('test.com', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail: 'bob#test.com' }),
})
but that doesn't work, my glassfish server doesn't get my parameters.
How should i do ?
It goes without saying that i don't want to make changes on the server side !
In your first example (using $.ajax()) you are not sending a JSON body. You are actually sending a query string. In your react example, you are sending a JSON body which would need to be handled differently by your server.
You will need to either change your server handler to actually accept JSON or you will have to send a query string with react which would look something like:
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: $.param({ mail: 'bob#test.com' }),
})
If you don't have access to jQuery you wouldn't be able to use $.param(). For this particular example, the query string you'd want to send would be
body: "mail=bob#test.com"
It is fairly straightforward to serialize data for a query string and creating a function that will do it pretty easy.
As a side note, in order to send a JSON body with an $.ajax() call, you would want to do something like this:
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: 'bob#test.com' }
contentType: "application/json",
)
Note the contentType parameter which actually tells jQuery how to format the body of the request

How do you format an AJAX request to an API with an authentication key using Mithril?

The following GET request works using jQuery:
$.ajax({
url: "https://yoda.p.mashape.com/yoda?sentence="+phrase,
headers: {"X-Mashape-Key": "superSecretKey", "Accept": "text/plain"},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
})
But the adaptation that follows using Mithril will not work:
Yoda.submit = function (phrase) {
console.log(phrase);
return m.request({
method: 'GET',
url: "https://yoda.p.mashape.com/yoda?sentence=" + phrase,
headers: {"X-Mashape-Key": "superSecretKey",
"Accept": "text/plain"}
});
}
I've tried different variations after consulting the documentation at https://lhorie.github.io/mithril/mithril.request.html and searching for similar examples. I'm considering using 3rd party libraries but thought I'd try here before I go too far down the rabbit hole. The error message that I get when I try to make an AJAX request is that I'm missing the API key even though it's right there.
UPDATE:
I've since learned, in addition to the answer marked below, that Mithril automatically parses API responses as JSON. Since I'm getting back a string response from this API, I have to include in my m.request object the following entry:
deserialize: function(value) {return value;}
Deserialize tells Mithril to return the response value as-is, not as JSON.
You need to use the config attribute:
m.request({method: 'GET', url: "https://yoda.p.mashape.com/yoda?sentence=" + phrase,
config: function(xhr, options) {
xhr.setRequestHeader("X-Mashape-Key", "superSecretKey")
xhr.setRequestHeader("Accept", "text/plain")
}}).then(function(data) {
console.log('success: ', data)
}, function(err) {
console.log('error: ', err)
})

How to include header in ajax request?

I need to include a header with a refresh token in an ajax call to the YouTube api. I am trying to send a delete request, to delete a movie I have on my account. This is my ajax call that fire on button click
jQuery.ajax({
type: 'DELETE',
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your requst');
}
});
I am receiving a 401 (unauthorized) erorr on return and it seems that I need to include my access token in the call. I was playing around with the google api playground looking at the request and response and this is what shows as the 'Request' being sent out
DELETE https://www.googleapis.com/youtube/v3/videos?id=3242343&key={YOUR_API_KEY}
Authorization: Bearer "access token"
X-JavaScript-User-Agent: Google APIs Explorer
Now from that request it looks like the there are headers that are being sent with the request, which hold the access token. This must be why I am getting a 401 error. How can I include those headers into my ajax request, so that my access token is passed along with the request? Thanks
I was able to pass along a header using this code below:
jQuery.ajax({
type: 'DELETE',
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID +'&key=api_key_here',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer access_token_here');},
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your request');
}
});
You can use beforeSend method and request.setRequestHeader. Take a look at the official documentation here.
P.S. should I post it as a comment?
Try add the paramenter data.
jQuery.ajax({
type: 'DELETE',
data: 'key=' + {YOUR_API_KEY},
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your requst');
}
});

Resources