31

I am trying to post form data from www.siteone.com to www.sitetwo.com via CORS. My ajax code is this:

<script>
$(document).ready(function(){
        $("#submit").live('click',function() {
            var url = "http://www.sitetwo.com/cors.php";
            var data = $('#form').serialize();
            jQuery.ajax({
                url : url,
                type: "POST",
                data : $('#form').serialize(),
                }).done(function(response){
                    alert(response);
                    }).fail(function(error){
                    console.log(error.statusText);
                    });
                return false;


});
});
</script>

and the file cors.php in www.sitetwo.com is as follows:

<?php
 header('Access-Control-Allow-Origin: *');
 header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
 echo "hai";
?>

But still Access-control-Allow-Origin error is thrown. The error thrown is this:

XMLHttpRequest cannot load http://www.sitetwo.com/cors.php. Origin http://www.siteone.com is not allowed by Access-Control-Allow-Origin. 

I came to know that, using CORS by just allowing the remote website via headers, we can use cross-domain request. But when I tried like this, error is thrown. Have I missed anything in here? Here is my request/response headers:

Response Headers
Connection  Keep-Alive
Content-Length  487
Content-Type    text/html; charset=iso-8859-1
Date    Fri, 23 Aug 2013 05:53:20 GMT
Keep-Alive  timeout=15, max=99
Server  Apache/2.2.15 (CentOS)
WWW-Authenticate    Basic realm="Site two Server - Restricted Area"
Request Headers
Accept  */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  43
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    www.sitetwo.com
Origin  http://www.siteone.com
Referer http://www.siteone.com/index.html
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0
Ganesh Babu
  • 3,250
  • 8
  • 31
  • 60
  • 1
    What value does `$_SERVER['HTTP_ORIGIN']` have? What value do you think it should have? Note that [`HTTP_ORIGIN` isn't mentioned in the documentation for `$_SERVER`](http://www.php.net/manual/en/reserved.variables.server.php) – Quentin Aug 22 '13 at 14:10
  • I even tried header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); but it didn't worked. – Ganesh Babu Aug 22 '13 at 14:11
  • 1
    1.) I have no idea what specific issue you are having. You will need to clarify that. 2.) As always, with these types of questions, show your request and response headers. – Ray Nicholus Aug 22 '13 at 14:18
  • @RayNicholus I have now edited the question and shown error that I have encountered. – Ganesh Babu Aug 22 '13 at 14:27
  • 1
    `$=jQuery.noConflict()` just looks wrong. You're telling jQuery to revert `$` back to it's original value, and then setting it back to jQuery. seems kinda pointless. – Kevin B Aug 22 '13 at 14:28
  • What browser are you testing in? – Kevin B Aug 22 '13 at 14:29
  • That should work actually – Hanky Panky Aug 22 '13 at 14:29
  • 1
    Still waiting for request/response headers. – Ray Nicholus Aug 22 '13 at 14:29
  • @KevinB I have removed it now. But still the error is thrown. – Ganesh Babu Aug 22 '13 at 14:30
  • @KevinB am testing in both chrome and firefox. – Ganesh Babu Aug 22 '13 at 14:31
  • @Ganesh We could probably help you out a lot quicker if you would simply post the request/response headers as requested (several times). Most likely, the problem is due to the fact that jQuery will send an X header (X-Requested-With) along with all requests by default unless you set the `crossDomain` option. The fact that your server isn't acknowledging this X header in a Access-Control-Allow-Headers response header is likely the problem. – Ray Nicholus Aug 22 '13 at 14:46
  • @RayNicholus Regret me... Actually I cannot understand what u mean by request/response headers. Are you asking about the response headers from browser?? – Ganesh Babu Aug 22 '13 at 14:53
  • Have a look at the network tab in Chrome, for example. – Ray Nicholus Aug 22 '13 at 14:55
  • It's really hard to read all of that. Why didn't you just edit your question? I'm also fairly sure that you're leaving out some headers, as an X-Requested-With header should also be present in the request. – Ray Nicholus Aug 22 '13 at 15:08
  • @RayNicholus very sorry for the delay. Here is the request/response header added in question – Ganesh Babu Aug 23 '13 at 05:58

3 Answers3

94

Finally, I myself have solved the problem explained in the question. The code that I have implemented for accessing header is incorrect.

The below mentioned two line code, when given, didn't work:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
?>

But handling CORS requests properly is a tad more involved. Here is a function that will respond more fully. The updated code is this :

 <?php
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    echo "You have CORS!";
?>

I have found from another post It worked....

Community
  • 1
  • 1
Ganesh Babu
  • 3,250
  • 8
  • 31
  • 60
  • @mplungjan may be I've got vote down because of the answer prevailing in some other page.. But I have solved my question and found the answer after a long analysis referring to other posts. Its still unwelcome by the community.. – Ganesh Babu Aug 28 '13 at 09:32
  • @mplungjan I have posted answer only after a day I posted this question. CORS haven't worked for me earlier. Everywhere in web, you can find only the two line header code found in question(php file). We should add some more to it for getting it enabled. Anyway, I have posted my answer only after it worked. – Ganesh Babu Aug 28 '13 at 11:40
  • 1
    I'd wager it's because `Access-Control-Allow-Origin: *` is wonderfully, beautifully, fantastically insecure – Bojangles Sep 24 '13 at 12:24
  • 7
    I agree that "Access-Control-Allow-Origin: *" is insecure but it is important to verify functionality first before locking things down. Everyone please lock down Access-Control-Allow-Origin after you get things up and running! :) – duskstriker Feb 11 '14 at 00:36
  • I have had issues with firefox using Access-Control-Allow-Origin: * It seems like FF wants the actual origin in the resoponse header not a wildcard, even though CORS, and Mozilla state that it should work on GET requests. – Karl Feb 12 '14 at 17:33
  • @duskstriker how to lock it down? so I can actually specific domains? is this the only way? http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains or there is better way to just config that header? – Ezeewei Aug 18 '16 at 23:11
  • @GaneshBabu While this solution works, it should be noted that not all browsers support the $_SERVER[HTTP_ORIGIN] and also it may not work in some specific requests. Here is an answer that adheres to W3C recommendations: http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains – padawanTony Sep 15 '16 at 11:23
  • Voted down because most important comment was not copied from original post: "Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one you want to allow, and if so...". Like this it does the same as `Access-Control-Allow-Origin: *` – Fabian Horlacher Feb 15 '19 at 10:52
  • this code work for me, and others answer not, why? Thaks. – Roger Sep 22 '19 at 03:18
4

To allow CORS for all:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

echo "You have CORS!";
3

Another reason is if you're missing a semicolon or something anywhere in your php, that CORS error message will be the only error that is displayed by the ajax, even if error reporting is on, while you can see the actual error by going to the php url in your browser.

Curtis
  • 2,173
  • 4
  • 33
  • 43
  • Thank you so much! Don't know why but I kept missing the log in the server error file regarding a missing ")" in my PHP code, and I kept getting that CORS error in the console. – Envayo Oct 19 '19 at 08:17