detox1978
asked on
XMLHttpRequest returns Access-Control-Allow-Origin
Hi All,
I have the following code;
That uses getJSON to grab some data from the server. This works well on the local server. However I need to run it via a different URL. When I do this I get the following error
A lot of people on the internet highlight is a cross site security issue.
I have full control over everything, so can make changes to the server (IIS7)
Any suggestions?
I have the following code;
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<table class="mGrid" id="jsondata">
<thead>
<th>ID</th>
<th>Customer</th>
<th>Contact</th>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url="https://www.mywebsite.com/getjson.php";
$("#jsondata tbody").html("");
$.getJSON(url, function(data){
format: "jsonp"
$.each(data.users, function(i,user){
var newRow = "<tr>"+"<td>-</td>"+"<td>"+user._9+"</td>"+"<td>"+user.Con_ConName+"</td>"+"</tr>" ;
$(newRow).appendTo("#jsondata tbody");
});
});
});
</script>
That uses getJSON to grab some data from the server. This works well on the local server. However I need to run it via a different URL. When I do this I get the following error
XMLHttpRequest cannot load https://www.mywebsite.com/getjson.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
A lot of people on the internet highlight is a cross site security issue.
I have full control over everything, so can make changes to the server (IIS7)
Any suggestions?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
After a little digging around I found an article that said to enable that setting on IIS I need to add the following to my web.config file;
I now see the following error message in the console log
followed by
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
I now see the following error message in the console log
GET https://www.mywebsite.com/getjson.php. 401 (Unauthorized)
followed by
XHR finished loading: GET "https://www.mywebsite.com/getjson.php".
ASKER
The web.config change I mentioned fixed the issue. The second 401 was because the web server didnt have anonamous access enabled.
many thanks
many thanks
ASKER
is there a way to tell what the URL it uses? maybe via a PHP page on the server it could connect to.
Alternatively, is there a way to switch it off/allow everyone