I have created and deployed my own webservice (WCF C#). I would like to call it using JavaScript, get data and populate a Chart.
Here is the code I pasted inside of a confluence HTML macro:
<script>
function fun()
{
var request = $.ajax({
url: "http://mydomain:port/MyService.svc/testRest",
data: "m=aa",
processData: true,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (e) {
console.log('error ' + e.status + ' ' + e.responseText);
}
});
}
var x = fun();
console.log(x);
</script>
The error I receive via developer console on Google Chrome (F12):
Mixed Content: The page at 'https://myconfluencesite.com/mypage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://mydomain:port/MyService.svc/testRest?m=aa'. This request has been blocked; the content must be served over HTTPS.
I have already whitelisted the service URL http://mydomain:port/MyService.svc/testRest. Assuming I activate SSL on my domain, would that fix the issue? Are there better methods?
The main idea is to load/populate tables/charts with external data. So I first started with my own service which returns a JSON structure. If that works, I can then use that structure to populate/load a HighCharts component for example.
Change http://mydomain:port/MyService.svc/testRest to https://mydomain:port/MyService.svc/testRest. Google Chrome, rightly, does not like that you have a page served through https which then calls a service using http. So, yes, activating SSL and using it will fix the issue. I would even say that no service should ever use a non-secure channel. Have your service require ssl.
Related
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).
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.
I am trying to call WCF Service from other project using the local address. I have two projects in same solution explorer. One project has the services and the other is a web application where I am using Ajax in javascript to call the WCF Service.
Following is my javascript code,
function sclick() {
alert("m here");
$.ajax({
type: "POST",
url: "http://localhost:4780/Service1.svc/myfunction",
contentType: "application/json; charset=utf-8 ",
dataType: "json",
success: success,
error: fail
})
}
function success(result) {
alert(result);
//alert("Success" + result.myfunctionResult);
}
function fail(result) {
alert("Fail..... " + result.statusText + ": " + result.status);
}
flow goes to success function but I get null in result object. URL in ajax part is the URL I got by viewing the service1.svc file in browser.
Can anyone please tell me where I am going wrong!
It works fine in same project. But cross domain is not working. When I call the service from other project it returns me null. I gave break point in service. Break point shows proper value but it does not come in my javascript code.
You shouldn't talk to a WCF service out of the box with a regaular Web service call, it is possible but more complicated. see: http://social.msdn.microsoft.com/Forums/vstudio/en-US/c896b564-7a9b-423d-a42d-d36c33c46e7d/consume-a-wcf-service-as-a-url
That is because WCF has an "overhead" of data used by the framework. Plus , WCF configuration may differ: It could be REST, SOAP or even Tcp or named pipe.
A more easy approach would be to generate the WCF client:
http://msdn.microsoft.com/en-us/library/ms733133.aspx
and than
call the client proxy from the ajax, instead of trying to call the server directly.
That is assuming you are running on a .Net web application.
otherwise, see how to talk to the service directly. This here an example on how to do this with Java:
http://hoonzis.blogspot.co.il/2011/07/consuming-wcf-services-with-java-client.html
And finally, another good answer which was suggested here and was later deleted, is to cofigure the WCF service to support REST API, like so:
http://www.codeproject.com/Articles/128478/Consuming-WCF-REST-Services-Using-jQuery-AJAX-Call
I think your issue may be that WCF doesn't support cross domain out of the box unless you enable CORS.
There's a good read with explanation and work around here: http://blogs.msdn.com/b/carlosfigueira/archive/2012/05/15/implementing-cors-support-in-wcf.aspx
Another alternative which may be easier for you would be to just drop the WebAPI into whichever project you're using, can do this in WebForms or MVC pretty easily.
Don't know about WCF web service but May be these lines of code which is for regular service , solve your problem
var jsonData = [YOUR JSON PARAMETER];
$.ajax({
async: false,
type: "POST",
url: [YOUR WEB SERVICE URL],
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ json: jsonData }),
dataType: "json",
success: OnSuccess,
failure: function(err) {
alert("Error : " + err.d);
}
});
function OnSuccess(data) {
alert("Success:" + data.d);
}
You can do one thing for that just need to set Access-Control-Allow-Origin & Access-Control-Allow-Headers in CustomeHeaders your web service web.config file.
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
If you want to allow only for specific domain , you can do that with specific value of domain instead of * value
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);
}
}
);
i have a web service in a server, and i could connect web service from any browser in remote machine or host machine. But i couldn't access the web service using ajax call in javascript, showing 403 forbidden error. I ran the script from the server itself. Below is the code i used.
$('div').live('pageshow',function(event, ui){
var username = 'vijay';
var password = 'vijay';
var domain = '';
var windowsuser = false;
// var dataObject = {};
// dataObject = {Username:username,Password:password,Domain:domain,WindowsUser:windowsuser};
$('#login').click(function(){
$.ajax({
type: "POST",
url: "http://xxx.xxx.x.xx/Y_NAME/REST/session.aspx",
data: ({Username:username,Password:password,Domain:domain,WindowsUser:windowsuser}),
// contentType: "application/x-www-form-urlencoded",
cache: false,
dataType: "json",
timeout: 5000,
success: onSuccess
});
});
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
});
function onSuccess(data)
{
//$("#resultLog").html("Result: " + data);
console.log(data[0].Name);
}
Here , after calling web service, it has to return JSON data, but it didn't return anything. In firebug, inside the function onSucess, it shows 'null' for data.
Do i miss anything here? Y does it show '403' forbidden error? Since i'm calling the scripts from the server where the web service located, i think its not cross domain issue. I'm using this in Jquery mobile. Help needed. Thanks in advance.
Your web service is probably not script enabled using the attribute:
[System.Web.Script.Services.ScriptService]
do you build the web-service through wizard? i think the web service url should be "http://xxx.xxx.x.xx/Y_NAME/REST/xxx.asmx"
I figured it.. There was problem with URL.