Cross domain ajax request - html

I want to get the HTML response page from the cross-domain URL.
for this I am using the ajax request as,
$.ajax({
type: 'GET',
url: "http://wcidevapps.com/salescentral/idisk/0001000383/iDisk",
dataType: "json",
success: function (response) {
$(response).find('li a').each(function () {
listHref.push($(this).attr('href'));
});
}
});
But after requesting it doesn't respond with any result back.

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
function NameAFunctionName() {
$.ajax({
url: 'http://wcidevapps.com/salescentral/idisk/0001000383/iDisk',
type: 'GET',
dataType: 'json',
headers: {
//WRITE IF THEIR HAVE SOME HEADER REQUEST OR DATA
},
crossDomain: true,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
</script>

Check documentation :
http://api.jquery.com/jQuery.ajax/
crossDomain (default: false for same-domain requests, true for cross-domain requests)
Type: Boolean
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5)

My suspicion is that you see the issue because the page you're requesting does not respond with a json(p) response, but responds with a redirect to:
http://wcidevapps.com/salescentral/idisk/0001000383/iDisk/
(note the trailing slash)
which then returns content type:
Content-Type:text/html;charset=ISO-8859-1
Edit: If your intention is to retrieve the above site's data cross-domain, for further parsing by your script, I suggest that you choose one of the following:
Assumption 1: YOU are in control of the pages on server "http://wcidevapps.com"
In that case, you have two options: Either add CORS header "Access-Control-Allow-Origin: *" to the response (and configure the client ajax() call with dataType:"html"), or create a special JSON(P) page that delivers the same data as JSON (with padding) (and configure the client ajax() call like in the OP, with dataType:"jsonp")
Assumption 2: YOU are NOT in control of the pages on server http://wcidevapps.com
In that case, the only option I can think of is setup a proxy on a site that you control. Have that proxy "proxy" the requests/responses to "http://wcidevapps.com", but add the CORS header "Access-Control-Allow-Origin: *" to the response (and configure the client ajax() call with dataType:"html")

If you are using asp.net web service then you need to add this to webconfig file;
<system.webServer>
<directoryBrowse enabled="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>

Related

How to call .asmx web service using plain html page

I am trying to call an asmx web service in plain html page. But not getting output. I'm not getting the exact problem. Here is my ajax code that I wrote to call that asmx web service.
function Getdet(Name)
{
alert('hellotest');
$.ajax({
type: "POST",
url: "http://192.168.1.20/myservice/service.asmx?HelloWorld", // add web service Name and web service Method Name
data: "{''}", //web Service method Parameter Name and ,user Input value which in Name Variable.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert('abcd1');
$("#spnGetdet").html(response.d); //getting the Response from JSON
},
failure: function (msg)
{
alert(msg);
}
});
}
Should I have to add anything in the code..?? Please let me know where I am going wrong in this above code.
ASMX pages are plain old Web Services and the output is (almost) always in XML format, so don't except JSON out of the box.
Plus, they don't work well on different domain call by default, you will need to ensure that the cross domain is correctly handled.
After all this is done, you will then use the call as:
success: function(response) {
// http://stackoverflow.com/a/1773571/28004
var xml = parseXml(response),
json = xml2json(xml);
$("#spnGetdet").html(json.d);
}

JSON works Locally but not with Servers

Here is my little first project as practice, having real trouble figuring out how to use JSON, took me a while to get it work locally but still no luck with servers, and tried few a including one i hosted, and even tried it with other hosted json files.
http://jsfiddle.net/Atlas_/Mgyc5/1/
$.ajax({
dataType: "json",
async: false,
url: "package.json", //https://www.dropbox.com/s/fmw63i4v7dtnx6t/package.json
'success': function (json) {
theQuiz = json.quiz;
console.log(json);
console.log(theQuiz);
}
});
When you access another domain be carefully with "Crossdomain".
To use with dropbox, try changing the URL to:
https://dl.dropboxusercontent.com/s/fmw63i4v7dtnx6t/package.json
Your code will be like this:
$.ajax({
dataType: "json",
async: false,
url: "https://dl.dropboxusercontent.com/s/fmw63i4v7dtnx6t/package.json",
success: function (json) {
theQuiz = json.quiz;
console.log(json);
console.log(theQuiz);
}
});
When you request 'dl.dropboxusercontent.com', you have this:
Access-Control-Allow-Origin: *
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control
"In this case, the server responds with a Access-Control-Allow-Origin:
* which means that the resource can be accessed by any domain in a cross-site manner."
Another options: Some websites (twitter, for example) work with "jsonp". http://en.wikipedia.org/wiki/JSONP or ..you can create your own proxy.

jQuery JSON parsererror even though JSON is valid

I am trying to pull in some external JSON phone list for a test I am doing locally.
JSON = https://www.o2.co.uk/shop/homepage/scripts/phoneList.json
I have read on a seperate thread that to overcome allow origin / cross domain issues you can pass 'callback=?' to the end of the url. This seems to work fine as now in the devtools network tab I can see the file being pulled in fine.
However, I never get it to go into the success callback function. It always brings back a parsererror.
The code is 100% valid according to jsonlint.com
A snippet of the code as below:
$.ajax({
type: 'GET',
url: 'https://www.o2.co.uk/shop/homepage/scripts/phoneList.json?callback=?',
contentType: 'application/json; charset=utf-8',
cache: true,
dataType:'json',
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
Any ideas welcome as I am well and truly stuck.
Thanks.
JSONP only works if the server supports it. What the server needs to do, is take your callback parameter and wrap the json data in a function call with that name.
So when https://www.o2.co.uk/shop/homepage/scripts/phoneList.json responds with
[{
"handset":"Alcatel 10.30 Black",
"link":"/shop/phones/alcatel/10.30-black/"
}]
https://www.o2.co.uk/shop/homepage/scripts/phoneList.json?callback=MyCallback should respond with:
MyCallback([{
"handset":"Alcatel 10.30 Black",
"link":"/shop/phones/alcatel/10.30-black/"
}]);
If the server doesn't do that, JSONP can't work. Perhaps O2 doesn't want you using their data.

Issue with Chrome calling cross domain jsonp resource via jQuery ajax

solved - it was Adblock Plus
I have a cross-domain OAuth scenario where I'm calling OAuth protected jsonp resources on a 3rd party api directly from JavaScript.
The client relies on my server (the site of origin) to generate signed request urls for OAuth resources on the provider. The client GETs these OAuth resources directly in an attempt to limit OAuth proxy duties of my server to simply generating signed resource urls and letting JS do the rest. Here's the JS:
myNamespace = {
callApi: function(signedRequest, callback) {
$.ajax({
url: signedRequest,
dataType: "jsonp",
type: "GET",
crossDomain: true,
jsonp: false,
jsonpCallback: callback,
cache: true,
async: true
});
},
usersCallback: function(jsonp) {
alert(jsonp);
},
getOAuthResource: function(resource, callback) {
$.ajax({
url: "/GetSignedRequest?resource=" + encodeURIComponent(resource + "&callback=" + callback),
success: function (signedRequest) {
myNamespace.callApi(signedRequest, callback);
}
});
}
}
Because the parameter order matters when signing the request, I include the callback manually so that it gets ordered & included in the signed request the server generates.
So an example usage would be simply,
myNamespace.getOAuthResource("/users?id=1", "myNamespace.usersCallback");
This is working in FireFox 20 and IE 10 - I get the alert msg & the expected json from the provider.
Chrome 26 refuses to perform the cross-domain call to the provider. In dev tools, the GET for the cross-domain resource immediately shows a Status of "(failed)" and the GET shows up in the console as an error.
If I subsequently ask Chrome to open this supposedly "failed" URL in a new window, it re-requests the URL directly on the provider and I get the expected jsonp response:
myNamespace.usersCallback({...})
Why won't Chrome perform the cross-domain call?

Calling WCF services from Javascript with UriTemplate and POST data

I've got a WCF 4.0 service that's currently set up for HTTP GET requests. I'm trying to modify it so that it uses POST, but keep backwards compatibility with the existing GET URIs. The web service is being called with jQuery and JSON data. Therefore, my requirements are the following:
Match the existing GET URI, presumably by using the UriTemplate parameter of the WebInvoke attribute.
Get the existing parameters from JSON data in the POST body, presumably by using WebMessageBodyStyle.Wrapped and WebMessageFormat.Json with the WebInvoke attribute.
Preferably have a way to pull large blobs of a data out of the POST body, probably also wrapped in a JSON object.
Alright, with that out of the way, here's what I've got so far. My little test service is called AjaxService and it's got one method called ToUpper. First, my web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication2.AjaxServiceAspNetAjaxBehavior">
<!--<enableWebScript />-->
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<remove scheme="http" />
<add scheme="http" binding="webHttpBinding" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication2.AjaxService">
<endpoint address=""
behaviorConfiguration="WebApplication2.AjaxServiceAspNetAjaxBehavior"
binding="webHttpBinding"
contract="WebApplication2.AjaxService" />
</service>
</services>
</system.serviceModel>
</configuration>
The following version of my ToUpper function allows me to pass its argument in the URI just like an HTTP GET.
[OperationContract]
[WebInvoke( UriTemplate="ToUpper?str={str}",
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
public string ToUpper(string str)
{
return str.ToUpper();
}
It's used in Javascript as follows and correctly returns "THIS IS FROM THE URI".
$(document).ready(function () {
$.ajax({
type: "POST",
url: "AjaxService.svc/ToUpper?str=this%20is%20from%20the%20uri",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("result: " + JSON.stringify(data));
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error", jqXHR, textStatus, errorThrown);
}
});
});
I can put the parameter in the POST data instead of the URI by removing UriTemplate="ToUpper?str={str}" from the WebInvoke parameters and using this javascript instead. It correctly returns "THIS IS FROM THE POST".
$(document).ready(function () {
$.ajax({
type: "POST",
url: "AjaxService.svc/ToUpper",
data: JSON.stringify({str:"This is from the POST"}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("result: " + JSON.stringify(data));
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error", jqXHR, textStatus, errorThrown);
}
});
});
I was hoping that if I left the UriTemplate="ToUpper?str={str}" in place and use the above javascript, it would be smart enough to pull the str parameter out of the POST data instead of the URI. Unfortunately, it just gives me an error 400. Is there a way to make that work?
One other thing I tried is using the optional Stream parameter to get at the raw contents of the POST data. But as this blog post points out, you can only get that stream if you set the content type to plain text instead of JSON. I could do that and manually parse the stream, but I think I'd also need to manually examine the URL to figure out if I got real values or defaults. Yuck.
If there's no way to make this work with the system bindings/settings, I was thinking about trying to write a custom binding that would be smart about pulling parameters out of the POST and URI, and also give you that raw stream even when you're using JSON. I spent a few hours trying to figure out how to do that but I'm stumped!
Has anyone else tackled this one or have any ideas on how to make it work? I can't imagine I'm the first one to have tried doing this, but I've come up empty handed after doing lots of searching.