Access JSON with JQuery which has authentication - javascript

I want to receive json from this API but it has authentication which username(nama pengguna) is "foo" and password(sandi) "foo". How I can receive it in my program? I use Jquery and eant build it with phonegap and build for Android
I am trying like this
$.ajax({
url: 'http://api.tabloidnova.com/1/subscribe/get?api_key=259225f04f4015746b03e1bad6238eaa&format=json&channel_id=110',
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization","Basic foo:foo");
},
dataType: 'json',
async: false,
success: function(data){
$.each(data,function(i,grab){
console.log(grab[i].article.node_id);
console.log("tes");
})
}
})
but in my ripple emulator it still give me unauthorized error. If I use without ripple emulator it can't work because I run it from localhost which has origin policy. Any suggestion?
SOLVED now. Finally I encode it my username and password first. Thanks

You will need to set the appropriate request header to pass the credentials. See for example here.
$.getJSON({
'url': 'http://host.com/action/',
'otherSettings': 'othervalues',
'beforeSend': function(xhr) {
//May need to use "Authorization" instead
xhr.setRequestHeader("Authentication",
"Basic " + encodeBase64(username + ":" + password)
},
sucess: function(result) {
alert('Done');
}
});

In javascript, with ajax we can do this way:
$.ajax({
'url': 'http://host.com/action/',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authentication", "Basic " + encodeBase64(username + ":" + password) //May need to use "Authorization" instead
},
sucess: function(result) {
alert('done');
}
});
Check the documentation for jQuery.ajax(). You will have more options to implement this.

Related

Google GMail API Error: No label add or removes specified

I'm building a small personal web app using the google API, but I'm having an issue with this endpoint: https://developers.google.com/gmail/api/reference/rest/v1/users.messages/modify
I'm trying to invoke this through AJAX, but it keeps telling me:
No label add or removes specified
I feel like I'm following the documentation specifications here, and the error isn't giving me any more information; I'm not sure what to do.
I've also tried adding the addLabelIds argument with no data, but it doesn't change anything.
I've tried looking this issue up but all of the solutions seem to relate to quirks of other API implementations and don't really seem to apply to my situation. Any help would be appreciated; it's pretty basic, but here's my AJAX requests code:
$.ajax({
url: "https://gmail.googleapis.com/gmail/v1/users/me/messages/" + messageId + "/modify",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + mailToken);
},
method: "POST",
data: {
"removeLabelIds": ["UNREAD"]
},
success: function(data) {
ele.removeClass("unread");
},
fail: function(data) {
console.log(data);
}
});
Okay, I found the solution myself; I'm just going to post it here in-case anyone else is having this issue.
The issue was that you have to make the request using Content-Type: application/json, and POST the request as a JSON string.
Here's the modified AJAX request that worked.
$.ajax({
url: "https://content-gmail.googleapis.com/gmail/v1/users/me/messages/" + messageId + "/modify?alt=json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + mailToken);
xhr.setRequestHeader("Content-Type", "application/json");
},
method: "POST",
data: JSON.stringify({
"removeLabelIds": [
"UNREAD"
]
}),
success: function(data) {
ele.removeClass("unread");
},
fail: function(data) {
console.log(data);
}
});

How to get oauth access_token with jQuery (localhost)?

I am trying to get access_token utilizing jQuery. Problem is, that I cannot get that token (server is running on localhost). Server works fine (I tried that with postman), but I cannot get it with jQuery.
Browser writes after clicking on the button.
The resource from “http://localhost:8080/oauth/token?callback=jQuery34105901959820360243_1562175129954&grant_type=password&client_id=my-client&client_secret=my-secret&username=test%40seznam.cz&password=Peter&_=1562175129955” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff).
jQuery function to get access_token
function authenticateUser(email, password) {
var body = {
grant_type: 'password',
client_id: 'my-client',
client_secret: 'my-secret',
username: "test#seznam.cz",
password: "Peter"
};
$.ajax({
url: 'http://localhost:8080/oauth/token',
crossDomain: true,
type: 'POST',
dataType: 'jsonp',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
header: {"Access-Control-Allow-Origin": "*"},
data: body,
complete: function(result) {
alert(result);
},
success: function(result) {
alert(result + " OK!");
},
error: function(result) {
alert(result + " CHYBA");
},
});
return true;
}
If the javascript file is served by the same server that gives out the tokens then there's no need to use the full url in your jquery ajax code (and there's no need to indicate crossDomain=true). It also seems that your server is expecting json content type instead of url-encoded
use
url: '/oauth/token',
crossDomain: false,
...
contentType: 'application/json; charset=UTF-8',
To make the request
Edit
Trye this way:
$.post("/oauth/token",body,
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
Hope this helps

How to access Neo4j dataset through Javascript?

I am wondering how I get access to my (example)dataset that I have on Neo4j through Javascript, i.e. I have a movie dataset, so I would like to get and receive queries through an local html page? As you might wonder, I am a very beginner to this and I really appreciate it if someone would explain it to me step by step :)
Thanks in advance
You can access your Neo4j graph database through the http transactional endpoint
http://neo4j.com/docs/stable/rest-api-transactional.html
and issue cypher queries to query your graph.
As it is a http endpoint, you can access it with normal ajax requests, an e.g. with jquery
var body = JSON.stringify({
statements: [{
statement: 'MATCH (n) RETURN count(n)'
}]
});
$.ajax({
url: "http://localhost:7474",
type: "POST",
data: body,
contentType: "application/json"
})
.done(function(result){
console.log(result);
})
.fail(function(error){
console.log(error.statusText);
});
With a local html page, I assume you mean jquery ?
In general for Javascript there are a number of drivers for neo4j, see http://neo4j.com/developer/javascript
If you want to look for jquery, check out http://jexp.github.io/cy2neo
(source: https://github.com/jexp/cy2neo/blob/master/scripts/neo.js#L7)
Note you need to add "authentifcation" too, it's done by an ajax function called beforeSend:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("neo4j"+ ":" + "yourNeo4jPassword"));
}}
also the path to the database is "http://localhost:7474/db/data/transaction/commit" and not "http://localhost:7474/"
So the final Solution is :
$.ajax({
url: "http://localhost:7474/db/data/transaction/commit",
type: "POST",
data: body,
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("neo4j"+ ":" + "password"));
}}
)
.done(function(result){
console.log(result);
})
.fail(function(error){
console.log(error.statusText);
});

Cross Domain AJAX POST / HTTPS / Header Authentication?

I have to issues:
1) I've tried using JsonP, but can't get POSTing to work. Essentially, I'm trying to authenticate with an API, passing a Base64-encoded namevaluepair in the header over HTTPS.
2) How do I pass this key/value in the header? Any help would be appreciated! Here is an example of what I want, though this obviously doesn't work:
// where does this go?
var headerString = 'user=' + encodeURIComponent(username + ':' + password);
$.ajax({
type: "POST",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
success: function(data) {
},
error: function(data){
}
});
add headers to ajax call:
var headerObj = {'user': encodeURIComponent(username + ':' + password)};
$.ajax({
type: "GET",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
headers: headerObj,
success: function(data) {
},
error: function(data){
}
});
The best way to do this is probably through a server side proxy on your own domain.
See this page for tips.
This way you will be able to get the response from the other server

Posting to YouTube API with jQuery

I am trying to post a request to the google authSub for youtube. I use jQuery for AJAX posts etc. When I make the POST I get a 405 error: "405 Method Not Allowed".
Here is my js:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
},
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
});
The page I am using in the API for this is here.
Here is what the error looks like:
Your data parameters for the request are misplaced see below:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
data: {
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
}
});
Now it may be something youre doing wrong additionally, but this for sure needs to be corrected.
Ah, here is a solution to the problem. If I make the request with the url built out and assigned as an href to an anchor or call it in window.open(); it works.
window.open('https://www.google.com/accounts/AuthSubRequest?scope=http://gdata.youtube.com&next=http://' + globalBrand + '/sitecreator/view.do&session=1');
As for why jQuery's method with the ajax was being rejected I know not. It seems to be an issue elsewhere also.
Solution to error HTTP HEADER OPTIONS in JQuery, this request is ok for me:
var word = 'search+word';
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/api/videos?q="+word+"&max-results=10&alt=json-in-script&format=5,
cache: false,
dataType:'jsonp',
success: function(data){
//json 'data' var treatment
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert("Not able to fetch the data due to feed unavailability!!!");
}
});
Reference: http://www.mohammedarif.com/?p=180

Categories