Call ASP.NET web service from a different domain via javascript - javascript

I want to call an asp.net web service's from a different domain with javascript.
Ex :
I have the site "www.abc.com", I want it to call the web service on "www.xyz.com" with some javascript I load from X domain.
First I add the script with this :
document.write(unescape("%3Cscript src=%27http://myscript.com/script.js%27 type=%27text/javascript%27%3E%3C/script%3E"));
This is the script.js file :
$.ajax({
type: "POST",
url: "http://www.xyz.com/Service1.asmx/InsertIt",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (response) {
alert(response);
}
});
function OnSuccess(response) {
alert(response.d);
}
I know Cross-domain calls from within client-side code are a no-no in all major browsers. To achieve that, I think you can use CORS.
Use CORS, ie. set Access-Control-Allow-Origin header to
http://your-caller-domain.com in the web
In this example, I know the caller domain : www.abc.com. but in the real life, I will never know the caller domain. I know there's other way to do a Cross-Domain call, ex : JSONP. But this technique is really complexe (for me).
So I am asking is there's an easy way to achieve a Cross-Domain call ?

The best and safest method is using your server side framework to do your http requests which you can then present to your JS. This negates any cross browser annoyances that client side calls inherit.
Eg:
AJAX hits www.abc.com/getdata.ashx.
Execute your request to www.xyz.com using below method.
Return a json string or plain text. It's up to you.
WebRequest for .NET. There is an example at the bottom.
Also look at HTTP handlers (.ashx) for doing requests. Not essential, but it's good to learn.

Check the documentation bellow, u'll be able to perform cross-domain requests
http://api.jquery.com/jquery.getjson/
$.getJSON( "http://www.xyz.com/Service1.asmx/InsertIt", function( data ) {
alert(data.d);
});

Related

how to pass a javascript code in jsonp format and execute

Can we use jsonp to overcome same domain policy of JS.
I need to run script from a domain x to run on domain y. So is it possible to send a script and execute ??
Yes, that is the entire point of JSONP.
There is no restriction on where you can load a script from (other then the usual http/https conflicts).
You can import a JS/CSS file from any other domain.
If you need to GET data from some other domain, you will need to get it through JSONP.
Please note that cross domain requests work only for HTTP/S GET and the only format of data accepted is JSONP.
e.g.
my code using jquery
$.ajax({
url: 'https://www.otherDomain.com',
type: "GET",
crossDomain: true,
data: parameters,
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
function localJsonpCallback(json) {
/* Do stuff */
}
The server side response needs to be in JSONP.

consuming PHP service returning valid json with $.ajax

I've been stuck on consuming a web service created in PHP, not sure what I'm doing wrong.. Ive created a fiddle example here : http://jsfiddle.net/e97AV/
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error.. in the browser when I visit the url it is returning valid json
My question is how would I know when to use jsonp or json? Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
heres the ajax code
baseUrl = "http://exclusivegetaways.co.za/api.php";
$.ajax({
type: "GET",
url: baseUrl,
data: {something : "something"},
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("works");
alert(result);
},
error: function (a,b,cc) {
alert(a+b+cc);
}
});
I've since been able to pull json data from the ajax error object?? like so:
baseUrl = "http://exclusivegetaways.co.za/api.php?something=something";
$.ajax({
type: "GET",
url: baseUrl,
dataType: "json",
success: function (res) {
alert("worked");
//alert(res);
},
error: function(jqxhr) {
try {
f = JSON.parse(jqxhr.responseText);
...valid json returned here
} catch(err) {alert(err);}
}
});
This is because of a security restriction that prevents Ajax from querying remote locations.
As a workaround to enable access to a remote location via Ajax, you could build a custom URL in your webApp (in PHP for instance) which queries the distant API and returns JSON.
Then, in your JavaScript, you call this URL (from your application) via Ajax.
First: Always look at your JavaScript error console.
XMLHttpRequest cannot load http://exclusivegetaways.co.za/api.php?location=provinces.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.
See also Ways to circumvent the same-origin policy
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error. in the browser when I visit the url it is returning valid json
This suggests that:
They don't support JSONP
They look at the HTTP headers and 404 your request to block access from Ajax (this isn't a good way to do that, the error code is misleading)
My question is how would I know when to use jsonp or json?
Usually by reading the documentation for the server you are trying to use
Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
Usually by working with whatever support is provided by the API provider (i.e. start with their documentation, then fall back to whatever means they provide for communicating with a human).
Due to Same Origin Policy your ajax request is allowed only if:
domain name, application layer protocol, and (in most browsers) port
number of the HTML document running the script are the same
In your case the application layer protocol is different, that's why your script fails.
Possible solutions are:
JSONP, which has to be provided by the server
CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)
Answer taken from this link

How to make an AJAX request to Dictionary.com's REST API using jQuery?

Dictionary.com provides absolutely no documentation on how to grab data from them. I'm trying to use jQuery's ajax requests, but those are not working.
They provide a URL through which I'm supposed to be able to use. I'll provide this below.
http://api-pub.dictionary.com/v001?vid=<VID>&type=random&site=dictionary
They also provide a key, which I assume that I place in the <VID> spot.
Could someone please tell me what I'm doing wrong with this? I'll provide the code I'm using below:
$("#btnGetData").click(function() {
$.ajax({
url: "http://api-pub.dictionary.com/",
type: "GET",
data: "v001?vid=<VID>&type=random&site=dictionary",
success: function() { alert("success") },
});
});
Could someone please tell me what I'm doing wrong?
You are not passing the data correctly. Also the request url is http://api-pub.dictionary.com/v001. Try this:
$("#btnGetData").click(function() {
$.ajax({
url: "http://api-pub.dictionary.com/v001",
type: "GET",
dataType: "jsonp", //For external apis
data: {"vid": <VID>,
"type":"random"
"site": "dictionary"},
success: function() {
alert("success") },
});
});
UPDATE: Maybe you're being blocked by the same origin policy as #thordarson note, in that case add:
dataType: "jsonp" to your ajax call.
Possibility 1
You don't have access to their API. According to their API page they're very selective about who they give access to their API.
We are selective about our API partners and approve use as well as
develop terms on a case-by-case basis. If you are interested in using
our API, please contact us directly [...].
Possibility 2
You're being blocked by the same origin policy. Browsers are generally very strict about requests made by JavaScript across different domains. This can be bypassed using Cross-origin resource sharing. This requires configuring the server you're requesting, so in this case it's not viable.
Your best bet would be to create a server-side script that requests the URL and then using AJAX to request the file.
Example in PHP, let's call this request_dictionary.php:
<?php
$vid = "Your API key";
$type = $_GET['type'];
$site = $_GET['dictionary'];
$request_url = "http://api-pub.dictionary.com/v001?vid=$vid&type=$type&site=$site";
echo file_get_contents($request_url);
?>
Note: You probably need to change this to fit your needs (error handling, 404s, caching etc.). This code is untested.
Then change your jQuery so that it requests your file.
$("#btnGetData").click(function() {
$.ajax({
url: "/request_dictionary.php",
type: "GET",
data: "type=random&site=dictionary",
success: function() { alert("success") },
});
});
Warning
Using an AJAX call without a proxy (as explained in possibility 2) will expose your API key. This is against Dictionary.com's API Terms of Service.
2.1 Dictionary.com will assign and deliver to your Customer Application an Application Key to access the API. All Calls must
contain such Application Key. The Application Key is uniquely
associated with each Customer Application and all versions, upgrades
and updates thereof. The Application Key is Confidential Information
as defined in these Terms and Conditions. You must maintain and keep
the Application Key in a secure, embedded manner not accessible by any
third party. The Application Key is fully revocable by Dictionary.com
at any time. Dictionary.com may block attempts to access the API with
an invalid or revoked Application Key.
I've updated the code in possibility 2 to conceal the API key by keeping it in the PHP file.
Update/Note: Simply passing dataType: 'jsonp' to enable cross-origin calls is not enough. The responding server needs to respond with an Access-Control-Allow-Origin header containing your domain (or a rule that includes your domain). Any configuration of this kind is out of your hand as the requester.
Update/Note 2: Upon investigating the returned headers from your request URL, I can see no evidence of Access-Control-Allow-Origin. This means that even if you had access to their API, you wouldn't be able to access it using AJAX. Full headers below:
GET /v001?vid=%3CVID%3E&type=random&site=dictionary HTTP/1.1[CRLF]
Host: api-pub.dictionary.com[CRLF]
Connection: close[CRLF]
User-Agent: Web-sniffer/1.0.44 (+http://web-sniffer.net/)[CRLF]
Accept-Encoding: gzip[CRLF]
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8[CRLF]
Accept-Language: en-US,en;q=0.8[CRLF]
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
Cache-Control: no-cache[CRLF]
Referer: http://web-sniffer.net/[CRLF]

cross-domain jquery 1.6.2 ajax call is trying to call from same domain

I have an api set up on another domain, domain B (api.domainb.com), and want to make a call to it from domain A (www.domaina.com). However, when I do a call from domain A to domain B via jquery ajax, jquery ends up trying to call www.domaina.com/api.domainb.com which obviously will return an error. Here is the relevant javascript code
$.ajax(
url: 'http://api.domainb.com',
type: 'GET',
dataType: 'jsonp',
data: {hello: 'world'},
crossDomain: true,
success: function(data){
alert(JSON.stringify(data))
},
error: function(error){
alert(JSON.stringify(error))
});
Eventually, the code in domain A and domain B will be on the same domain, but for now, I need to make a cross-domain call. Any suggestions as to how to make this work?
You're just missing the protocol so that the Ajax call knows it's a different domain and not a relative URL. Try using url: 'http://api.domainb.com'.
You cannot make cross-domain calls; browsers simply do not allow it in general. However, the reason you're seeing the behavior you describe is that your URL is missing the "http://" prefix.
There are some things you can do with fairly new HTML5 APIs to sort-of "get permission" to do cross-domain calls.
edit #Dan points out correctly that while XMLHttpRequest (what people usually call "ajax") won't do cross-domain stuff (CORS aside), it's possible to leverage the fact that <script> tags can reference other domains in order to put together a service. The server-side code has to be different, however. (That's usually called "JSONP".)

Can AJAX request data from a remote server?

Can I use XMLHttpRequests in JavaScript to request a file on a different server than the one from where the request was made?
Thank you.
You need to use a method that is called as JSONP.
One of the best ways is to use jQuery to reduce the code and worries between your page and the server, and all you need to do is:
$.ajax({
dataType: 'jsonp',
data: 'id=10',
jsonp: 'jsonp_callback',
url: 'http://myotherserver.com/getdata',
success: function () {
// do stuff
},
});
Only if the remote server supports JSONP or HTTP Access-Control headers.
Public JSON API's (like the ones provided by Google.com, Facebook.com, etc) often do.

Categories