jQuery JSONP ajax, authentication header not being set - javascript

I'm trying to make an ajax request to the google contacts API with the following setup:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
headers: {
'Authorization': 'Bearer ' + token
},
success: function(data, status) {
return console.log("The returned data", data);
}
});
But the Authentication header doesn't seem to get set. Any ideas?

I had the same problem recently. Try this:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
success: function(data, status) {
return console.log("The returned data", data);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + token); }
});
EDIT: Looks like it can't be done with JSONP. Modify HTTP Headers for a JSONP request

When authentication is needed in a cross domain request, you must use a proxy server of some sort.
Since using dataType: jsonp results in the HTTP request actually being made from the script that gets added to the DOM, the headers set in the $.ajax will not be used.

Is seems that most of the OAUTH2 REST resources accept the access_token parameter as part of the request url
http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param
please, try the following code instead:
$.ajax({
dataType: 'jsonp',
url: url,
data: {
'access_token':token.access_token
},
jsonpCallback: 'thecallback',
success: function(data){
_cb(data);
},
error: function(d){
_cb(d);
}
});

Just do this (jquery 2.0, but should work in previous versions)
$.ajax({
url: "/test",
headers: {"Authorization": "Bearer " + $('#myToken').val()}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus) {
alert("error: " + textStatus);
});

Related

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 parse response as json object for cross domain ajax call?

I'm making a cross domain ajax call. When I heat the link directly from my browser, I get the json strin as follows:
But when I'm making an ajax call to this same URL, I'm not getting the json in my response. My ajax request is as follows:
$.ajax({
url: "http://172.16.201.14:801/api/apiclearing?trackNo=" + $scope.BillClearingModel.BillTrackingNo + "&&tokenNo=~Ice321",
dataType: 'jsonp',
success: function(response) {
console.log(response);
alert("Success");
},
error: function(response) {
console.log(response);
alert("Failed");
}
});
What Im getting in console is as follows:
Full Object is as follows:
What I'm missing here? Thanks.
Would you mind trying this:
var datastring = { "trackNo" : "160822000037" };//try this
//var datastring = "trackNo=160822000037"; //or this
$.ajax({
type: 'POST',//you may try the GET type
url: "https://172.16.201.14:801/api/apiclearing",
dataType: 'json',// try jsonp as well
data: datastring,
contentType: 'application/json',
crossDomain: true, //newly added
success: function(data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(JSON.stringify(data));//to string
alert("Success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Status:"+ textStatus + " Error:" + errorThrown);
}
You may consider as well to add Access-Control-Allow-Origin to your server like Access-Control-Allow-Origin: http://yourdomain-you-are-connecting-from.com in php

Correct way to retrieve JSON from API using jQuery's ajax()

Here's what I'm trying to achieve: I want my site to send a request to an API that retrieves a JSON with a random quote which then gets converted to HTML and appears on the site. ATM I've managed to solve it by three different ways with their Pros and Cons:
1. Using JSONP
$(document).ready(function() {
newQuote();
function newQuote() {
$.ajax({
dataType: "jsonp",
crossDomain: true,
contentType: "application/json; charset=utf-8;",
jsonpCallback: "parseQuote",
url: "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=parseQuote"
})
.done(function(json) {
$("<h3>").text(json.quoteText).appendTo(".quote");
$("<div class=\"content\">").html(json.quoteAuthor).appendTo(".quote");
})
.fail(function(xhr, status, errorThrown) {
alert("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
})
};
$("#newquote").on("click", function() {
$(".quote").empty();
newQuote();
});
});
Pro: Works in all Browsers.
Con: AFAIK JSONP has some security Issues.
2. Using CORS
$(document).ready(function() {
newQuote();
function newQuote() {
$.ajax({
dataType: "json",
crossDomain: true,
contentType: "application/json; charset=utf-8;",
url: "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json"
})
.done(function(json) {
$("<h3>").text(json.quoteText).appendTo(".quote");
$("<div class=\"content\">").html(json.quoteAuthor).appendTo(".quote");
})
.fail(function(xhr, status, errorThrown) {
alert("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
})
}
$("#newquote").on("click", function() {
$(".quote").empty();
newQuote();
});
});
Pro: Is the correct way to do it
Con: Only works on Safari
3. Using Cross-Origin Proxy
$(document).ready(function() {
newQuote();
function newQuote() {
$.ajax({
dataType: "json",
crossDomain: true,
contentType: "application/json; charset=utf-8;",
url: "https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json"
})
.done(function(json) {
$("<h3>").text(json.quoteText).appendTo(".quote");
$("<div class=\"content\">").html(json.quoteAuthor).appendTo(".quote");
})
.fail(function(xhr, status, errorThrown) {
alert("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
})
}
$("#newquote").on("click", function() {
$(".quote").empty();
newQuote();
});
});
Pro: Works with all browsers
Con: Is really slow, takes like 2-3 seconds to do the request each time I press the button.
So that's the situation, I want you to help me 'cause I don't know which one is the correct way or if there's a better way to make it work in all browsers but without sacrificing speed or security.

HTTP Authentication failing in AJAX for postmates api

I'm trying to use the postmates API, which first requires us to authenticate ourselves using http basic authentication. The username field in the code below is where we inserted our private API key.
<script>
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); }
});
});
</script>
The error we are getting is
XMLHttpRequest cannot load
http://api.postmates.com/?callback=jQuery112008309037607698633_1462052396724&_=1462052396725.
Response for preflight is invalid (redirect)
need the authentication
https://postmates.com/developer/docs#authentication
The actual header that is used will be a base64-encoded string like
this:
Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==
Try to
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); },
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==");
}
});
});
I don't test because jsfiddle block external petitions.

Receive serialized in php data by using ajax

I have a php script, which return serialized in php data. And I try to receive this data by using $.ajax() method from jQuery 1.7. Here is the example.
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res) {
alert('COMPLETE() done');
console.log(res);
}
});
In console I see only
Object { readyState=0, status=0, statusText="error"}
So, what I do wrong? Could you help me please?
UPD
Interesting notice: if I use JSONP dataType request can receive data, but can't process it.
Here is an example.
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
dataType: 'jsonp',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Instead of complete: use success: then res will be the returned data from your ajax request.
Remember to use error: as well incase there is an error with you call, as it seems that there might be in your console output.
Code:
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Your code is probably fine, but you're trying to violate the same origin policy. Basically, if your site is http://aaa.com/, you cannot make AJAX called to http://bbb.com/.
There are a few ways around it:
Getting around same origin policy in javascript without server side scripts
But most of them require that both sides play nice.
The response is the second parameter of complete function:
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res,response) {
alert('COMPLETE() done');
console.log(response);
}
});
More info: http://api.jquery.com/jQuery.ajax/
You should also consider using JSON, not php serialized data

Categories