Reputation: 4783
I have a simple PHP file that performs a MySQL query and returns a result.
At the top of the PHP file, I have this code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
?>
I know that this is working as if I were to inspect in Chrome, if I look at the request headers that come back in the 'Network' tab I can see the header was set successfully.
Now I make the call from my JavaScript file on another domain using jQuery:
var getMyResults = $.ajax({
url: "http://mydomain.uk/myphpfile.php",
data: {something: "someData"},
dataType: "JSON",
type: "GET"
});
Every single time I run this code from the JavaScript file I get the follow error:
XMLHttpRequest cannot load http://mydomain.uk/myphpfile.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myotherdomaincallingthefile.uk' is therefore not allowed access.
Why is this happening?
Upvotes: 0
Views: 167
Reputation: 4783
After a few hours of investigation I found the issue with the help of t3chguy in the comments.
My AJAX request URL: "http://mydomain.uk/directory"
Correct, working cross origin AJAX: "http://mydomain.uk/directory/"
A single extra "/" fixed the issue.
Why?
With the help of http://redirectcheck.com/ I saw that without the '/' Apache was making a redirect which meant that the cross origin header wasn't present on that initial request, hence the error.
Upvotes: 0
Reputation: 1018
There is a redirect going on before you get to the final page, which sends the header, locate it; if it is in .htaccess you can add this to the .htaccess file:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</ifModule>
or your other option is in your Ajax call to use the final URL, which would supply the headers without any redirects in the way.
Upvotes: 1