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
Related
I am currently using postman to make an API request that pushes body data. I can get this to work either using "x-www-form-urlencoded" or "raw". See examples below:
I'm trying to convert this to an ajax javascript request but unsure on how to format the body/data text. Here is my script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {
" grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "
},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});
Any help would be appreciated
There's a mismatch here as you're setting the Content-Type header to JSON, yet you're sending form-urlencoded. You need to use one or the other consistently.
If you want to explicitly use JSON, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***'
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
If you want to use a form-urlencoded string, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
Note in the above examples that the first argument to the error handler is not the request or response data as your example seems to expect. I've amended that part to accept the correct arguments.
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.
I've racked my brain over this and I cant seem to figure out the solution so ask humbly for your assistance please. I'm using the restlet client on chrome which uses a cURL command to GET json from a server. I need to convert this curl command over to AJAX, and I'll provide as much code as I'm allowed to. Could you please help me by converting this over to jQuery's Ajax?
cURL Command:
curl -i -L -X GET \
-H "Authorization:Basic base64username:base64password" \
'https://internalserverurl'
Here's what I have for my jQuery AJAX Method:
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
function getData() {
$.ajax({
url: "https://internalurl",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
processData: false,
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
},
error: function (data) {
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push(key + ":" + data[key] + "<br><br>");
}
}
alert(strBuilder.join(""));
$('#errordiv').html(strBuilder);
}
});
}
Thank you all for your assistance.
I said it in the comments, but you can use the $.ajax function and set your headers in the beforeSend block.
$.ajax({
url: 'https://internalserverurl',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization':'Basic base64username:base64password');
}
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"
});
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.