I need to make an AJAX request from a website to a REST web service hosted in another domain.
Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.
The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.
Here is the JavaScript code that makes the asynchronous call:
var serviceUrl = "http://myservicedomain"; var payload = "<myRequest><content>Some content</content></myRequest>"; var request = new XMLHttpRequest(); request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers request.setRequestHeader("Content-type", "text/xml"); request.send(payload);
How can I have this work in other browsers beside Internet Explorer?
For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.
Cross-origin resource sharing (or CORS) can be used to make AJAX requests to another domain.
You can allow Cross Domain Ajax calls to an application by just registering a new filter and then configure it to Allow-Origin : {your domain's} or you can use a wild card “*” to allow the calls from all domains.
Re: CORS issue after ajax post requestYour server needs to not only allow POSTs from the origin using Access-Control-Allow-Origin (origin = your Marketo LP domain including protocol, like https://pages.example.com), it also needs to allow the Content-Type header using Access-Control-Allow-Headers.
maybe JSONP can help.
NB youll have to change your messages to use json instead of xml
Edit
Major sites such as flickr and twitter support jsonp with callbacks etc
The post marked as the answer is erroneous: the iframes document is NOT able to access the parent. The same origin policy works both ways.
The fact is that it is not possible in any way to consume a rest based webservice using xmlhttprequest. The only way to load data from a different domain (without any framework) is to use JSONP. Any other solutions demand a serverside proxy located on your own domain, or a client side proxy located on the remote domain and som sort of cross-site communication (like easyXDM) to communicate between the documents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With