0

I am trying to get response from an api that is not in my domain.

$.ajax({
                type: "GET",
               url: "http://stage.developmentcheck.org/api/project_monitoring_detail",
               data:{'project_id':'16'},
               error: function (response) {
                        alert('Error: There was a problem processing your request, please refresh the browser and try again');
                },
                success: function (response) {
            console.log(response);
               }
        });

So the error says Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://stage.developmentcheck.org/api/project_monitoring_detail?project_id=16. This can be fixed by moving the resource to the same domain or enabling CORS. So far I have only used html but since I am using ajax to get data from api, please enlighten me where should i enable CORS and how? I have tried adding Header set Access-Control-Allow-Origin "*" in httpd.conf but it did not work.

Pravin
  • 1,671
  • 5
  • 23
  • 36

2 Answers2

1

http://enable-cors.org/

You can indeed do it via apache. Don't forget to enable it on both sides (server - client). Check the response headers in the network tab of your Developer tools

Server side:

To add the CORS authorization to the header using Apache, simply add the following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:

Header set Access-Control-Allow-Origin "*"

Did you added it inside a <Directory>, <Location>, <Files> or <VirtualHost> ? you can't just drop it in the httpd.conf. The other option is drop it in a .htaccess file in the folder you want (e.g. the api folder)

jQuery Example:

$.ajax({
    type: "GET",
    url: "http://stage.developmentcheck.org/api/project_monitoring_detail",
    data:{'project_id':'16'},
    crossDomain: true,        
    error: function (response) {
        alert('Error: There was a problem processing your request, please refresh the browser and try again');
    },
    success: function (response) {
        console.log(response);
    }
});
VDP
  • 6,340
  • 4
  • 31
  • 53
0

You can do it with PHP. Just add header("Access-Control-Allow-Origin: *"); in the beginning of your PHP-script. Though this will not work if your PHP-settings are somehow messed up or controlled by some strict sysadmin, etc.

Swiffy
  • 4,401
  • 2
  • 23
  • 49
  • No indication that OP is using php. And what do you mean with "messed up"? Headers can always be set unless the are already set earlier (e.g. in certain frameworks), not? – VDP Jul 16 '14 at 06:58
  • @VDP By messed up I meant I've had some sysadmins, for example, somehow disabling configs like access-control-allow-origin through PHP. – Swiffy Jul 16 '14 at 07:02