jQuery AJAX Cross Domain with BASIC Authentication - javascript

I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.
What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.
<script type="text/javascript">
$(document).ready(function() {
var tok = 'username' + ':' + 'password123';
hash = btoa(tok);
authInfo = "Basic " + hash;
$.ajax({
url: "http://username.beanstalkapp.com/api/changesets.json",
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
type: "GET",
async: false,
crossDomain: true,
dataType: "json",
success: function(html){
console.log(html);
},
error: function(html){
console.log('error');
}
});
});
</script>
If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!

You will need to make proxy for cross-domain ajax requests.
Usual scenario looks like this:
Client send ajax request to server
Your server forwards request to external/remote server
Waiting on response from remote server
Parse and process response from remote server
Send response back to client
If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.

you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.

Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.

Related

jQuery AJAX call sending as OPTIONS and missing Authorization header

I'm starting to get stumped on this. I'm developing a C#.NET Web API service and frontend application to use it. I've been having a lot of difficulty using a token to authenticate my requests and jQuery seems to be having trouble. I can get a token just fine, but jQuery won't add it to an Authorization header in further requests.
My setup is an index.html page with several jQuery Mobile pages inside it. It starts on a '#login' page, which sends a request to my /Token URI with a username, password, and grant type. This is successful and the return is the token. The page changes to '#home' and a test ajax call is sent to /api/values to grab value. The problem is that instead of adding a header called 'Authorization', jQuery adds an 'Access-Control-Request-Headers' with the value 'accept, authorization' instead. At first I thought it was a CORS issue, but the request works fine when I use Advanced Rest Client in Chrome to send the request.
AJAX Call from '#Home'
$.ajax({
url: 'http://slalomtest2.azurewebsites.net/api/values/',
type: 'GET',
async: true,
dataType:"json",
beforeSend: function(request){
request.withCredentials = true;
request.setRequestHeader("Authorization", "Basic " + Token);
},
success: function(result){
console.log(result);
},
error: function(request, error){
$.mobile.changePage("#login");
}
});
The bad request the AJAX sends
This is what it looks like from Advanced Rest Client in the same browser
Thanks in advance for the help, I've been banging my head against the wall all day.

jQuery cross domain ajax call - Interpreted as script but transferred with MIME type text/xml

Trying to make a REST web service call using an ajax call. Whenever I try to run it, I receive the error, Interpreted as script but transferred with MIME type text/xml. Here's my code ("website" is actual website where web service is):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function testCall() {
var webMethod = "website";
var un = 'un'
var pw = 'pw'
var parameters = "username=un&password=pw&change_ticket_number=CRQ000000011334&restuser=TEMPESP&restpass=restpw";
$.ajax({
url: webMethod,
type: 'Post',
data: parameters,
crossDomain: true,
username: un,
password: pw,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType: 'jsonp',
success: function(data) {
alert('Success: ' + data);
},
error: function(errorThrown){
alert('Try again ' + errorThrown);
}
});
}
I have been searching all over the web and this website for something like this but I haven't had any success.
I have initially had my dataType as "xml" as that's what the web services provdies but changed it to "jsonp" when I read about cross domain calls.
The parameters are what the web service is looking for. If I was to open an internet browser and put the url + parameters, it does show me the xml message.
I'm not sure how much control I have over the web service itself so my hope would be to figure out a way on how to translate this back to xml after jsonp successfully brings it over.
So the question remains, am I able to change my code in order to make this work, leaving the web service as is? If it's truly not possible, what needs to be done to the web service? Keeping in mind xml is being used.
Thank you for any help you can provide.
The JSONP data format is a JavaScript program consisting of a function call (to a function defined in the URL) with the requested data as the argument.
You are getting the error because you are making a JSONP request and getting XML.
Change the server so it returns JSONP or change the JavaScript so it expects XML (and also change the server so it gives your site permission to read the XML using CORS).

Salesforce OAuth with REST API using Javascript

I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

JQuery ajax call to cross-domain webservice

I would like consume cross-domain web-service from client with jquery
function TestService() {
$.ajax({
url: "http://service.asmx/GetGeoCompletionList",
data: { "prefixText":"eka", "count":"10", "contextKey":"Trace_0$Rus" },
dataType: "jsonp",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.statusText);
}
});
}
At the error hander I have:
textStatus=parseerror
XMLHttpRequest has status 200 and readyState 4
errorThrown is jQuery16103495572647140...78197139 was not called
I've spent on it for a lot of hours and couldn't make it work. Can u help me?
UPDATED
Thanks, I change to GET, and fix my data string.
Service returns valid JSON object. I can see it at firebug on other site, which consume this service. But that site is getting common json(since it has one domain).
So, if the web-service returns valid JSON(not jsonp), I can't use the same method with jsonp? What can I do for consiming json web-service from other domain?
That string you are passing and claiming is JSON isn't JSON.
Only " characters may be used to quote strings.
Also, you can't make a cross domain JSON-P POST request.
You cannot do cross-domain POST requests using JSONP. JSONP works by adding script tags to the page. script tags always fetch their source using GET HTTP requests. You won't get any data posted.
Summary of problems:
Make sure you're using valid JSON
as #Quentin mentioned.
Make sure you're using GET requests, as
#lonesomeday mentioned
Make sure the response from the server is
JSONP, as seen here

Categories