Search code examples
javascriptjqueryajaxhtmlsame-origin-policy

Can't make AJAX call to local webserver from HTML5 app


I'm trying to make a simple AJAX request from an HTML5 app to a local webserver. However, because the client code was not served from the webserver, I'm getting the "Origin null is not allowed by Access-Control-Allow-Origin" error.

I've tried everything described in the following post, but still doesn't work: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin

If I post my server code on an Internet-hosted server, the client app works. But I'd like it to work with my local MAMP server which is running on the same laptop.

1) On the local webserver, I added the following to my PHP controller:

header('Access-Control-Allow-Origin: *');

2) Here's my HTML5 client app. JSONP should not been needed since the server supports CORS.

<html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
    <base href='http://192.168.15.12/'></base> <!-- local MAMP server -->     
    <script>

        $(document).ready(function() {
                $('#leadButton').click(function(){

                    $.getJSON(
                        'get/leaderboard',
                        function(data){
                            var leader;

                            leader = "<div> The top leader is from local webserver is: " +  data[0].name + "</div>";
                            $('#leaderboard').append(leader);
                            console.log(data);
                        }
                    );     
                });
        });
    </script>
</head>

<body>
    <div id="leaderboard">Leaderboard
        <button id="leadButton">Get Leaderboard</button>
    </div>
</body>

3) When I call the client app (file:///Users/John/Desktop/index.html) from Chrome, and click on the leadButton" button, here are the resulting request/response headers:

Request URL:http://192.168.15.12/get/leaderboard
Request Method:OPTIONS
Status Code:403 Forbidden

Request Headers
Access-Control-Request-Headers:Origin, X-Requested-With, Accept
Access-Control-Request-Method:GET
Origin:null

Response Headers
Connection:Keep-Alive
Content-Length:227
Content-Type:text/html; charset=iso-8859-1
Date:Thu, 03 Nov 2011 19:03:27 GMT
Keep-Alive:timeout=5, max=100
Server:Apache

What am I missing? Thanks for your help.


Solution

  • I found the problem:

    The request to the local webserver (192.168.15.12) requires the full URL to specified in the $.getJSON request: "http://192.168.15.12/get/leaderboard"

    The "base" tag did not prepend "http://192.168.15.12/" to the URL in the jQuery call.

    I also needed to add the following Apache config to my .htaccess file to enable Cross-Origin Resource Sharing (CORS) (doing this in PHP did not work reliably):

     Header set Access-Control-Allow-Origin *