api imgur cannot favorite image - javascript

Before asking my question , i try several method, google it my issue and decided to post here my problem.
I use imgur api 3 with javascript, i have a function to make favorite an image but without success.
Here some sample of what i did
with my client id:
$.ajax({
type: "POST",
url: 'https://api.imgur.com/3/image/'+ currentId +'/favorite',
//headers:{
// 'Authorization':'Client-ID Client-id'
//},
success: function(data) {
console.log(data);
},error:function(error,a,b){
console.log(error,a,b);
}
});
Result : permission denied, 403
with my access_token:
$.ajax({
type: "POST",
url: 'https://api.imgur.com/3/image/'+ currentId +'/favorite',
headers:{
'Authorization ': 'Bearer '+params.access_token
},
success: function(data) {
console.log(data);
},error:function(error,a,b){
console.log(error,a,b);
}
});
Result : "SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Authorization ' is not a valid HTTP header field name."
And without the headers i have : "Authentication required", 401
here the link for favorite an image
Thanks in advance for your help.

Related

How to make a REST API Request with Ajax and session token?

I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});

Successful ajax request which goes in error callback instead of success

I have an AJAX request which aims at my API but the response goes in to the error callback instead of the success callback and I don't know why. The status response header is the success status (200). Can you help me please?
I can avoid this issue with the complete callback and if the status code is 200 or 400 I will display what I want, but it will not solve the real problem. It's actually what I did but it's not the best solution.
$.ajax({
url: 'http://api.asaplace.v-labs.fr/users/me/cards/' + numCard,
dataType: 'json',
type: 'DELETE',
headers: {
'Authorization': 'Bearer ' + this.state.token
},
success: function() {
console.log("success");
},
complete: function(xhr) {
alert("carte supprimée avec succès");
console.log("error");
},
});
The request
enter image description here
I found the error the "dataType" was in JSON I put it in xml and it works thank's all for your help

Microsoft QnA Maker API Error Resource Not Found

I am sending a POST request using JS for Micosoft QnA Maker API. But it is returning a JSON file with Error Resourse Not Found
{ "error": { "code": "ResourceNotFound", "message": "The requested resource was not found." } }
Although I am doing everything correct according to the API still getting the same error.
I am using the code in JS as shown below:
<script type="text/javascript">
$(function() {
var params = {
"question": "is qna maker free?",
"top": 3
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/XXXX/generateAnswer?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","XXXX");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
This code is returning alert("error") and also showing the following message in console:
westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/XXXX/generateAnswer?question=is+qna+maker+free%3F&top=3:1 POST https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/XXXX/generateAnswer?question=is+qna+maker+free%3F&top=3 400 (Bad Request)
I am referring to this link
I have seen that there Response 400 says that "Argument question is not specified." But I have specified the question.
What's wrong with my code? I am quite sure that there's must be something wrong with this in my code.
"question": "is qna maker free?",
"top": 3
When I visit this link
It also shows the same JSON file with the error.
you have in your code:
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/XXXX/generateAnswer?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","XXXX");
},
type: "POST",
// Request body
data: params, //replace {body} with the params variable
dataType: "json" //add this line
})
You might also want to handle the response with success/error functions so it will look like this:
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/XXXX/generateAnswer?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","XXXX");
},
type: "POST",
data: params,
dataType: "json",
success: function(data){
alert("success");
},
error: function(e){
console.log(e);
}
})

Facebook Graph jQuery AJAX call to post a photo on user's behalf

I'm trying to post a photo on the users behalf. I've been searching the web for the last 4 hours and I'm out of ideas.
JS:
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})
the error function outputs the following:
[object Object]|error|Bad Request
I think there must be something wrong with the ajax request itself, but I can't figure out what it is. I've reconstructed my request using the Facebook Graph API explorer and everything works fine there. Any ideas?
Need to define the correct data type in the ajax request ( jsonp ), just try this will work :
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
dataType: "jsonp", //Just add this line ( jsonp not json ),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})

Get location from JSON in javascript

I am working now in a phonegap android application, I need the user's current address, so that i have used this
JSON api.
This is my code to get data for location updates from JSON api
$.ajax('http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true', {
dataType: 'jsonp',
timeout: 3000,
data: {
_method: 'GET'
},
success: function (data,status) {
if (data._status != 200) {
console.log('received error', data._status);
// handle error
}else{
console.log('received data', data);
// do something useful with the data
}
},
error: function(data,status) {
var myObject = JSON.stringify(data);
console.log("Data Returned is " + myObject);
console.log("Status is " + status);
alert('error');
},
complete: function(data, status) {
alert('complete');
}
});
Every time it goes on error section , then the complete section, never goes into the success part.
the console output is :
12-10 11:11:34.393: I/Web Console(10620): Data Returned is {"readyState":4,"status":404,"statusText":"error"} at file:///android_asset/www/index.html:263
12-10 11:11:34.393: I/Web Console(10620): Status is error at file:///android_asset/www/index.html:264
Can anyone tell me, where exactly the problem is ?
If I remember correctly the default security policy in PhoneGap is to block all network access. You need to whitelist http://maps.googleapis.com.
The api you request does not support jsonp, the final request will like this:
http://maps.googleapis.com/maps/api/geocode/json?callback=jQuery18309743240959942341_1386656119920&latlng=26.9008773,75.7403539&sensor=true&_method=GET&_=1386656120107
with the callback param, but the output is still json, not javsscript file like
jQuery18309743240959942341_1386656119920(jsonDataHere...)
Take a look at this: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse, it request url like this
https://maps.googleapis.com/maps/api/js/GeocodeService.Search?5m2&1d40.714224&2d-73.96145200000001&7sUS&9sen&callback=_xdc_._4cni6z&token=46423
And the output is:
_xdc_._4cni6z && _xdc_._4cni6z( { ....
That's jsonp.
ajax_call ='http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true';
$.ajax({
type: "GET",
url: ajax_call,
cache:false,
dataType: "json",
success: function(response){
$.each(response.results, function(key, value) {
//alert(value.formatted_address);
console.log(value.formatted_address);
});
}
}).done(function() {
})

Categories