I'm trying to get access to education.com API data. However, I keep receiving an error the error states:
XMLHttpRequest cannot load http://api.education.com/service/service.php?f=schoolSearch&key=mykey&sn=sf&v=4&city=Atlanta&state=ga&Resf=json. Origin is not allowed by Access-Control-Allow-Origin.
My code is the following:
$(function(){ $.getJSON('http://api.education.com/service/service.php?f=schoolSearch&key=mykey&sn=sf&v=4&city=Atlanta&state=ga&Resf=json', function(data) { console.log(data); }); });
Can someone help me please?
In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple: Create a Chrome browser shortcut. Right click short cut icon -> Properties -> Shortcut -> Target.
In simple words, this error occurs when we try to access a domain/resource from another domain. To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.
The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.
An article on Cross Domain AJAX issue a while back here:
CROSS DOMAIN AJAX REQUEST WITH JSON RESPONSE FOR IE,FIREFOX,CHROME, SAFARI – JQUERY
The easiest way to handle this if you have control of the responding server is to add a response header for:
Access-Control-Allow-Origin: *
This will allow cross domain AJAX. In PHP you'll want to modify the response like so:
<?php header('Access-Control-Allow-Origin: *'); ?>
you can just put Header set Access-Control-Allow-Origin * setting on apache conf or htaccess file it just work like a charm
Important Note:
The wildcard is going to allow any domain to send requests to your host. I recommend replacing the asterisk with a specific domain that you will be running scripts on.
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