Jquery Ajax Cross Domain

jQuery AJAX cross domain

Use JSONP.

jQuery:

$.ajax({
url:"testserver.php",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
}
});

PHP:

<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>

The echo might be wrong, it's been a while since I've used php. In any case you need to output callbackName('jsonString') notice the quotes. jQuery will pass it's own callback name, so you need to get that from the GET params.

And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?' to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).

how to solve cross domain in ajax

You need to use JSONP to make CROSS DOMAIN Requests.

Please read:

Loading cross domain endpoint with jQuery AJAX

Make cross-domain ajax JSONP request with jQuery

Usages of jQuery's ajax crossDomain property?

The default for crossDomain is as follows:

false for same-domain requests, true for crossDomain requests

The data-type is interpreted differently depending on the value for the crossDomain setting:

"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options

Because you are using jsonp instead of json you won't see any difference in your tests.

When do I need to set the crossDomain property ?

If you are making a same domain json request, and your site may redirect the request to another domain to serve the response (via HTTP 3XX), then you should set the crossDomain property to true so the response can be read by your calling script.

This gives you the advantage of retrieving JSON when making same origin requests, and the functionality of JSONP when making cross-origin requests. If CORS is active on the domain you redirect to then you can set jsonp: false in the request options.

Examples

Making a request from example.com to example.org.

  • crossDomain automatically set to true.
  • Data type set to jsonp.

Result: JSONP returned by example.org.

Making a request from example.com to example.com.

  • crossDomain automatically set to false.
  • Data type set to jsonp.

Result: JSONP returned by example.com.

Making a request from example.com to example.org.

  • crossDomain automatically set to true.
  • Data type set to json.

Result: JSONP returned by example.org.

Making a request from example.com to example.com.

  • crossDomain automatically set to false.
  • Data type set to json.

Result: JSON returned by example.com.

Making a request from example.com to example.org.

  • crossDomain automatically set to true.
  • Data type set to json.
  • jsonp is set to false.
  • example.org does not support CORS for example.com

Result: CORS error returned by browser.

Making a request from example.com to example.com, example.com redirects AJAX to example.edu.

  • crossDomain manually set to true.
  • Data type set to json.

Result: JSONP returned by example.edu.

Making a request from example.com to example.org.

  • crossDomain automatically set to true.
  • Data type set to json.
  • jsonp is set to false.
  • example.org does support CORS for example.com

Result: JSON returned by example.org.

Making a request from example.com to example.com, example.com redirects AJAX to example.edu.

  • crossDomain automatically set to false.
  • Data type set to json.
  • example.edu does not support CORS for example.com

Result: CORS error returned by browser.

Loading cross-domain endpoint with AJAX

jQuery Ajax Notes

  • Due to browser security restrictions, most Ajax requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

There are some ways to overcome the cross-domain barrier:

  • CORS Proxy Alternatives
  • Ways to circumvent the same-origin policy
  • Breaking The Cross Domain Barrier

There are some plugins that help with cross-domain requests:

  • Cross Domain AJAX Request with YQL and jQuery
  • Cross-domain requests with jQuery.ajax

Heads up!

The best way to overcome this problem, is by creating your own proxy in the back-end, so that your proxy will point to the services in other domains, because in the back-end not exists the same origin policy restriction. But if you can't do that in back-end, then pay attention to the following tips.



**Warning!**

Using third-party proxies is not a secure practice, because they can keep track of your data, so it can be used with public information, but never with private data.


The code examples shown below use jQuery.get() and jQuery.getJSON(), both are shorthand methods of jQuery.ajax()



CORS Anywhere

2021 Update

Public demo server (cors-anywhere.herokuapp.com) will be very limited by January 2021, 31st

The demo server of CORS Anywhere (cors-anywhere.herokuapp.com) is meant to be a demo of this project. But abuse has become so common that the platform where the demo is hosted (Heroku) has asked me to shut down the server, despite efforts to counter the abuse. Downtime becomes increasingly frequent due to abuse and its popularity.

To counter this, I will make the following changes:

  1. The rate limit will decrease from 200 per hour to 50 per hour.
  2. By January 31st, 2021, cors-anywhere.herokuapp.com will stop serving as an open proxy.
  3. From February 1st. 2021, cors-anywhere.herokuapp.com will only serve requests after the visitor has completed a challenge: The user (developer) must visit a page at cors-anywhere.herokuapp.com to temporarily unlock the demo for their browser. This allows developers to try out the functionality, to help with deciding on self-hosting or looking for alternatives.

CORS Anywhere is a node.js proxy which adds CORS headers to the proxied request.

To use the API, just prefix the URL with the API URL. (Supports https: see github repository)

If you want to automatically enable cross-domain requests when needed, use the following snippet:

$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});

$.get(
'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});


Whatever Origin

Whatever Origin is a cross domain jsonp access. This is an open source alternative to anyorigin.com.

To fetch the data from google.com, you can use this snippet:

// It is good specify the charset you expect.
// You can use the charset you want instead of utf-8.
// See details for scriptCharset and contentType options:
// http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
$.ajaxSetup({
scriptCharset: "utf-8", //or "ISO-8859-1"
contentType: "application/json; charset=utf-8"
});

$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent('http://google.com') + '&callback=?',
function (data) {
console.log("> ", data);

//If the expected response is text/plain
$("#viewer").html(data.contents);

//If the expected response is JSON
//var response = $.parseJSON(data.contents);
});


CORS Proxy

CORS Proxy is a simple node.js proxy to enable CORS request for any website.
It allows javascript code on your site to access resources on other domains that would normally be blocked due to the same-origin policy.

  • CORS-Proxy gr2m
  • CORS-Proxy rmadhuram

How does it work?
CORS Proxy takes advantage of Cross-Origin Resource Sharing, which is a feature that was added along with HTML 5. Servers can specify that they want browsers to allow other websites to request resources they host. CORS Proxy is simply an HTTP Proxy that adds a header to responses saying "anyone can request this".

This is another way to achieve the goal (see www.corsproxy.com). All you have to do is strip http:// and www. from the URL being proxied, and prepend the URL with www.corsproxy.com/

$.get(
'http://www.corsproxy.com/' +
'en.wikipedia.org/wiki/Cross-origin_resource_sharing',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});


CORS proxy browser

Recently I found this one, it involves various security oriented Cross Origin Remote Sharing utilities. But it is a black-box with Flash as backend.

You can see it in action here: CORS proxy browser

Get the source code on GitHub: koto/cors-proxy-browser

jQuery ajax request being block because Cross-Origin

Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.

http://learn.jquery.com/ajax/working-with-jsonp/

Try example

$.ajax({
url: "https://api.dailymotion.com/video/x28j5hv?fields=title",

dataType: "jsonp",
success: function( response ) {
console.log( response ); // server response
}

});

Jquery $.ajax fails in IE on cross domain calls

Could you check if the problem with IE relies on not defining security zones to allow cross domain requests? See this microsoft page for an explanation.

OTOH, this page mentions that IE7 and eariler cannot do cross domain calls, but IE8 can, using a different object than XMLHttpRequest, the one JQuery uses. Could you check if XDomainRequest works?

EDIT (2013-08-22)

The second link is dead, so I'm writing here some of its information, taken from the wayback machine:

XDomainRequest
Supported: IE8

Rather than implement the CORS version of XMLHttpRequest, the IE team have gone with there own propriety object, named XDomainRequest. The usage of XDomainRequest has been simplified from XMLHttpRequest, by having more events thrown (with onload perhaps being the most important).

This implementation has a few limitations attached to it. For example, cookies are not sent when using this object, which can be a headache for cookie based sessions on the server side. Also, ContentType can not be set, which poses a problem in ASP.NET and possibly other server side languages (see http://www.actionmonitor.co.uk/NewsItem.aspx?id=5).

var xdr = new XDomainRequest();
xdr.onload = function() { alert("READY"); };
xdr.open("GET", "script.html");
xdr.send();


Related Topics



Leave a reply



Submit