J. Doe J. Doe - 1 month ago 4
Javascript Question

Getting Json with javascript

Json hosted online and should be accessed by a link:

{
response: "yes"
}


Getting Json on a device:

<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script> $(document).ready(function () {
var url = 'link is here';
$.getJSON(url, function (data) {
alert(data.response);

});
});</script>


Shows nothing. Please advice.

Answer

It has to do with the fact that the php needs to grant access. For testing purposes you can add this line on top of your php code:

header('Access-Control-Allow-Origin: *'); 

However this is not safe at all. Therefore you need to write it somehow like this:

header('Access-Control-Allow-Origin: http://mysite1.com');
header('Access-Control-Allow-Origin: http://example.com');
header('Access-Control-Allow-Origin: https://www.mysite2.com')  

This is all mentioned and explained in here: how to bypass Access-Control-Allow-Origin?

Comments