Cross Domain AJAX POST / HTTPS / Header Authentication? - javascript

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

Related

Update (PUT) a JSON object with ajax - PrestaShop

I am trying to update a JSON object (e.g: customer). But, I have the following error:
"NetworkError: 405 Method Not Allowed - http://prestashop/api/..."
This is my code (index.js):
var testWebService = angular.module('testWebService', []);
testWebService.controller('testWebServiceCtrl', function ($scope, $http) {
var $baseDir = "http://prestashop/api";
var $objectDir = "customers";
var $idObjectDir = "1";
var $keyDir = "F517VWPRREG7TA25DEY8UIZT8V79E5OV";
var $urlDir = $baseDir + "/" + $objectDir + "/" + $idObjectDir + "?ws_key=" + $keyDir + "&output_format=JSON";
// TEST DE LA METHODE PUT SUR L ID D UN CUSTOMER
$.ajax({
type: "PUT",
url: $urlDir,
dataType: "json",
async: false,
contentType: "application/json; charset=utf-8",
data: {"id": "93"},
crossDomain: true,
success: function () {
console.log("Ok PUT");
},
error: function() {
console.log("Erreur PUT");
}
});
});
Before, I tried to GET the id of an object (same: customer) and I succeeded with an almost similar method.
I precise that I gave rights about "customer" in Advanced Settings / webservice (for method GET, PUT, POST ...).
Thanks in advance for your help, I tried so many things, but whitout success.
PS: If you have any suggestion about my code to "clean" it, you were pleased.
My webservice JSON:
{"customer":{"id":1,"id_default_group":"3","id_lang":"1","newsletter_date_add":"2013-12-13 08:19:15","ip_registration_newsletter":"","last_passwd_gen":"2015-06-08 03:38:27","secure_key":"7036cdf99ea12125ad1b3789f298f686","deleted":"0","passwd":"2e372235eb5213bc004ce72bcfef16a2","lastname":"DOE","firstname":"John","email":"pub#prestashop.com","id_gender":"1","birthday":"1970-01-15","newsletter":"1","optin":"1","website":"","company":"","siret":"","ape":"","outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":"","is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2015-06-08 09:38:27","date_upd":"2015-06-08 09:38:27","associations":{"groups":[{"id":"3"}]}}}
EDIT:
When I tried with the method GET, I did:
$.ajax({
type: "GET",
url: $urlDir,
dataType: "json",
async: false,
success: function (data) {
$scope.customer1 = data;
console.log("Ok GET");
console.log(data);
},
error: function() {
console.log("Erreur GET");
}
});
Reading the status code definition of the http protocol, try adding the following property to the ajax request:
$.ajax({
type: "PUT",
...
beforeSend: function (xhr) {
xhr.setRequestHeader("Allow", "GET, HEAD, PUT, DELETE");
},
...
});
PS: If you have CORS disabled on your server, look this answer and set the headers to allow your server access to requests from different origins.

Adding HTTP Header to AJAX get request

I am trying to make an AJAX call to an API which requires an HTTP header (REST parameters).Currently no data is being returned. I think what is giving the most difficulty is understanding setRequestHeader, not even sure if its necessary. In this example , msdn it takes 2 string arguments: oReq.setRequestHeader("Content-Type", "text/xml") but then where does the authorization header go? Please Help
Currently I have this:
var baseURL = "https://api.azuga.com/azuga-ws/v1/live/location.json";
var header = "Authorization: Basic 0JRGDJW587832"; //Made up number
$.ajax({
url: baseURL,
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader(header);},
success: function(data){
console.log(data);
}
});
Did you tried:
var baseURL = "https://api.azuga.com/azuga-ws/v1/live/location.json";
$.ajax({
url: baseURL,
dataType: 'json',
headers: { 'Authorization': 'Basic 0JRGDJW587832' },
beforeSend: function(xhr){xhr.setRequestHeader(header);},
success: function(data){
console.log(data);
}
});
?
also note that your header is a string, so setRequestHeader is not taking two parameters!

Access JSON with JQuery which has authentication

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.

setting the request header content-type with POST

I am trying to send some JSON data to the server but I keep getting a 415 error: Unsupported Media Type. This is my ajax call
$.ajax({
type: "POST",
url: 'http://mywebsite.com?'+"token="+token+"&account="+account+"&version=1.0&method=put",
dataType: 'jsonp',
contentType: "text/json",
processData: false,data: JSON.stringify(jsonData),
success: function () {
alert("Thanks!");
}
})
}
I noticed that in the request header there is no content-type listed. So how do I set the content type for the request header?
Thanks!
I think that your url is corrupted, you missed / and ?:
url: 'http://www.mywebsite.com/?'+"token="+token+"&account="+account+"&version=1.0&method=put",
Moreover you shuldn't use global urls (with http), because they are blocked by browser...
url: "?token="+token+"&account="+account+"&version=1.0&method=put",
You cannot post data this way outside url. Try following code
$.getJSON("http://www.yourwebsite.com/PersonCount.aspx?id=" + id + "&dt=" + dt + "&t=" + time + "&callback=?", function(data) {
/// Your response from {data}
});

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