PHP-AJAX CORS Fails due to Access-Control-Allow-Origin
<p>I am trying to make an AJAX call (CORS) using the below code:</p>

<pre><code>$.ajax({
    type: "POST",
    url: 'http://localhost/MySpace',
    success: function(result) {
         console.log(result);
    },
    error: function() {
         console.log("error");
    },
});
</code></pre>

<p>I am running the above code from:</p>

<pre><code>http://127.0.0.1/Test/index.html
</code></pre>

<p>The PHP Code written at <code>http://localhost/MySpace</code> is as below:</p>

<pre><code>&lt;?php
    header("Access-Control-Allow-Origin: *");
    echo "Hello";
?&gt;
</code></pre>

<p>As per my understanding, this should have worked. However I am getting this error:</p>

<pre><code>XMLHttpRequest cannot load http://localhost/MySpace. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1' is therefore not allowed access.
</code></pre>

<p>What should I do make this work? Or am I doing something entirely wrong?</p>

<p>As per suggestions to debug the request I tried making a curl request:</p>

<pre><code>curl -i http://127.0.0.1/MySpace/
</code></pre>

<p>And in response I can see that <code>Access-Control-Allow-Origin</code> is marked as <code>*</code>:</p>

<pre><code>HTTP/1.1 200 OK
Date: Fri, 13 May 2016 05:59:19 GMT
Server: Apache/2.4.18 (Unix) OpenSSL/1.0.2g PHP/5.6.19 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By: PHP/5.6.19
Access-Control-Allow-Origin: *
Content-Length: 5
Content-Type: text/html; charset=UTF-8
</code></pre>

<p>As per the comment I added the below code to my <code>.htaccess</code>:</p>

<pre><code>Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</code></pre>

<p>@Edit:</p>

<p>This is my Response Header:</p>

<pre><code>HTTP/1.1 301 Moved Permanently
Date: Fri, 13 May 2016 09:26:44 GMT
Server: Apache/2.4.18 (Unix) OpenSSL/1.0.2g PHP/5.6.19 mod_perl/2.0.8- dev Perl/v5.16.3
Location: http://localhost/elasticservice/
Content-Length: 240
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
</code></pre>

<p>This is my request header:</p>

<pre><code>POST /elasticservice HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 0
Cache-Control: max-age=0
Accept: */*
Origin: http://127.0.0.1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36
Referer: http://127.0.0.1/test/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,hi;q=0.6
</code></pre>