Imgur API Version 3 JavaScript upload example - javascript

All the examples I find online are of earlier versions of the Imgur API or non JS code all of which uses an API key which doesn't exist in the newer API. Instead you get a client_id and secret. Anyone have example code that shows how an image can be uploaded to Imgur through JavaScript (or jQuery) using version 3 of their API?

$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {
'Authorization': 'Client-ID YOUR_CLIENT_ID'
},
type: 'POST',
data: {
'image': 'helloworld.jpg'
},
success: function() { console.log('cool'); }
});

Building on #vin's example here is one:
$(document).ready(function() {
$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {
'Authorization': 'Client-ID a1b2c3d4e5'
},
type: 'POST',
data: {
'image': image
},
success: function(data, status) {
console.log("Data: " + data.data.link + "\nStatus: " status);
console.log(data.data.link)
}
});
});
This lets you save the url to the file.

Related

Best practice for nesting ajax calls

I am creating a simple app using Spotify REST API and JQuery where users can find an artist, and then it will show info about the artist, related artists, and most listened to songs on-page. I created 3 ajax calls which u can see below and everything works, but I think that it can be written in a better way (promises maybe?).
The first ajax call gets id from the server and create some DOM elements. The second two ajax calls need id to run and also create DOM elements. There is also a delete button that should delete DOM elements built from the data of each ajax call.
Is it possible to have it nested using the best practice or this is the only way possible?
artistForm.submit((e) => {
e.preventDefault();
let inputSearchQuery = artistInput.val();
let searchQuery = encodeURI(inputSearchQuery);
$.ajax({
url: `${baseUrl}search?q=${searchQuery}&type=artist`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
}).done((resp) => {
const artistId = (resp.artists.items[0].id);
// working with data and appending them on DOM
$.ajax({
url: `${baseUrl}artists/${artistId}/top-tracks?country=CZ`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
}).done((resp) => {
// working with data and appending them on DOM
$.ajax({
url: `${baseUrl}artists/${artistId}/related-artists`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
}).done((resp) => {
// working with data and appending them on DOM
deleteArtist.click(() => {
// need to have acces to data from every ajax call.
})
});
});
});
});
Given your work case, you could consider the following method:
artistForm.submit(async (e) => {
e.preventDefault();
let inputSearchQuery = artistInput.val();
let searchQuery = encodeURI(inputSearchQuery);
let artist = await $.ajax({
url: `${baseUrl}search?q=${searchQuery}&type=artist`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
const artistId = artists.items[0].id;
let topTracks = await $.ajax({
url: `${baseUrl}artists/${artistId}/top-tracks?country=CZ`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
let relatedArtists = await $.ajax({
url: `${baseUrl}artists/${artistId}/related-artists`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
deleteArtist.click(() => {
// need to have access to data from every ajax call.
});
});
This is assuming you are using jQuery 3.0 or higher. If not you can find a nice wrapper function here.
If you want to learn more about promises and async await I recommend the following video's: JavaScript Promises In 10 Minutes - by Web Dev Simplified
and The Async Await Episode I Promised - by Fireship.
If you have questions about the code above, please add a comment.
I hope this helps you continue with your project (and that you've learn something along the way 👍).

add new record in CRM using web API

I am trying to add records to CRM using Javascript but getting:
401 Unauthorized Error.
My question is how to get the token and use it inside the JavaScript function.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You need add Authorization information in Http Header. Here is an example if you use JWT.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization':'Bearer your token here'
},
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You have to add a header with the bearer token like this:
$.ajax({
(...)
headers: {
"Authorization": "Bearer " + token
},
(...)
In order to get a token you have to register an application in Azure Active Directory first, in the same tenant as your Dynamics 365 instance. Check this link if you need a thorough step by step guide to do it.
After registering you application in AAD you also have to add some code to do the authentication with Azure and getting the token. ADAL.js does this job for you, but keep in mind that it prompts the user to manually add his username and password in a office 365 popup. This is called interactive authentication and as far as I know it can't be avoided.
For a full HTML + JS working example click here.

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.

Best method for getting JSON from REST API with Token

I have a rest API which has some nice JSON I want. I want to be able to call the API from a script within some HTML and pull out the JSON thats relevant to me.
What would be my best approach?
Something like the below using ajax? but i can't find a nice working example.
I have a token for my API so its vital I can use this. A curl command would be perfect, alas I cant do that. Eventually what I do will be used in a chrome extension.
jQuery.ajax( {
url: 'https://my-api.com/rest/v2/users/'
type: 'GET',
data: { content: 'testing test' },
beforeSend : function( xhr ) {
xhr.setRequestHeader( "Authorization", "BEARER " + xxxxxxxxx );
},
success: function( response ) {
// response
}
} );
Try this
var myJson;
$.ajax( {
url: 'https://my-api.com/rest/v2/users/'
type: 'GET',
data: { content: 'testing test' },
headers: { 'Authorization' = 'Bearer ' + token },
success: function( response ) {
myJson = response;
}
} );
Here there is the official explanation of the getJSON() method with some examples
https://api.jquery.com/jQuery.getJSON/
var authorizationToken = "xxxxxxx";
function xRequest(endpoint, method, options) {
$.ajax($.extend({}, {
type: method,
dataType: "json",
url: "https://api.xxxx.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.xxxxxx+json;version=2"
}
},
options));
}
This works

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"
});

Categories

Resources