SPBeginer SPBeginer - 7 months ago 37
Ajax Question

How to access Rest API data hosted at other domain. Cross domain issue

I can successfully access data from my local Rest api through JQuery, But when i tried to access data from remote Rest API (hosted at other domain) through JQuery, i got the error as Undefined.
How i solve cross domain problem ?

This is how i am using through JQuery.

function GetCompanyName(id) {
jQuery.support.cors = true;
url: 'http://novacompanysvc.azurewebsites.net/api/companies',
type: 'GET',
data:{ id:id },
dataType: "text/xml",
success: function (data) {
if (window.DOMParser)
parser=new DOMParser();
else // Internet Explorer
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
error: function (x, y, z) {


This error happens because the API end point you are accessing does not implement CORS. If you run your code in Chrome and look at the console, you will see an error:

XMLHttpRequest cannot load http://novacompanysvc.azurewebsites.net/api/companies?id=1. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

The solution is to change the API end point to set the Access-Control-Allow-Origin header to either the wildcard * or to the domain where the page using the JavaScript code will be served from.