WCF Service call from ajax(cross domain) - javascript

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

Related

Call Custom REST API from Confluence

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.

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.

Read RSS XML in javascript (cross domain)

I want to read rss(xml) file but without using google rss feed.
i have try jsonp but it download the file and it throw a error "Uncaught SyntaxError: Unexpected token < "
$.ajax({
type: "GET",
url:'https://news.google.com/?output=rss',
//url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: "xml",
contentType: "text/xml; charset=utf-8",
headers: { "Access-Control-Allow-Origin":"*",},
success: function(xml) {
alert("success");
}
});
plz guys help me..
$.getJSON("//ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?", {
num: 10,
q: url
}).done(function (data) {
console.log(data);
});
Notes:
You're overdoing it. Don't try to specify information on the client side that the server actually has to supply (content type, allow origin headers, data type).
You don't want XML, you want JSON.
The name for cross-origin JSON requests is JSONP.
jQuery implements that for you if you use the getJSON() API method. You don't have to do anything besides adding "callback=?" to the URL.
Use jQuery Deferred callbacks (then, done, fail and always). They allow your code to become a lot more flexible.
Have a look at the documentation, too. https://developers.google.com/feed/v1/jsondevguide
You basically can't implement a web client RSS reader because you can't be sure that content providers will set the correct CORS header for their feed(s) ; My advice would be to not waste your time reading through endless CORS/JSONP lectures (and trying misleading code) but implement a server solution (like, say Pétrolette) and move on.

Referencing a WCF Service in the web.config file via javascript

I have an asp.net webforms website and a wcf service. I use jQuery to perform my AJAX operations to/from the WCF service like so:
$.ajax({
type: "POST",
url: "192.168.1.24/ServiceMain.svc/" + serviceName,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{}",
cache: true,
success: function (json)
{
//Success operation here
},
error: function ()
{
//Error operation here
}
});
All is fine right now. However, I want to be able to do a testing and production environment, both of which will be hosted on a different server with different IP Addresses.
Clearly, hard-coding the URL to point to the correct WCF service will become a tedious problem if left unchecked. Therefore, I was wondering what was the best approach in retrieving the WCF Service's URL. I thought about using the web.config file with something like the following:
<%=ConfigurationManager.AppSettings("SomeWCFKey")%>
However, I am not sure how to correctly reference the address in my web.config file:
<endpoint address="http://192.168.1.24/ServiceMain.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IServiceMain"
contract="ServiceMain.IServiceMain"
name="BasicHttpBinding_IServiceMain" />
Any help would be appreciated, thanks.
Hi i think you are actully want to read endpoint address that you can get by this code
private List<string> GetEndpoints()
{
var endpointList = new List<string>();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);
foreach (ChannelEndpointElement endpoint in serviceModel.Client.Endpoints)
{
endpointList.Add(endpoint.Address.ToString());
}
return endpointList;
}
Here is pont that descirpt mroe in detail : Getting WCF Bindings and Behaviors from any config source
this might also help you : Programmatically enumerate WCF endpoints defined in app.config

Categories