Anthony
Anthony

Reputation: 3218

Why XMLHttpRequest doesn't work with "www."?

I have following code:

var params = {
            cache:false, 
            dataType:"json", 
            type:"GET",
            url: "/order.php",
            error: function(data){
                dump(data);
            },
            success: function (data){
              alert('ok');
            },
            data:{
                js:1
            }
        };

$.ajax(params);

So if I run example.com it gets work perfect. But if I run www.example.com I get an error via my function dump(). Google console shows an error:

XMLHttpRequest cannot load =1345470451769">http://example.com/order.php?js=1&tariff=247&=1345470451769. Origin http://www.example.com is not allowed by Access-Control-Allow-Origin

What does it mean?

So I don't need any permanent redirect from www.domain.com to domain.com.

Thanks in advance for any help.

update 1: I added function:

function getBaseUrl()
{
   var baseUrl = '';
   baseUrl += location.protocol + '//';
   baseUrl += location.hostname;

   return baseUrl;
}

and change url: "/order.php" on url: getBaseUrl() + "/order.php"

got the same error. Am I doing something wrong here?

Update 2: I added this one to htaccess file:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin http://sample.com http://www.sample.com
</IfModule>

It seems my hosting doesn't support it, because I still get an error for www.

Upvotes: 2

Views: 582

Answers (2)

PhonicUK
PhonicUK

Reputation: 13864

The error you've got there means that you can't make a XMLHttpRequest from one domain to another unless the target domain specifies in its response header that you're allowed to do this. It's a security measure enforced by the browser.

The entire domain has to match, so example.com can't make a XMLHttpRequest request to www.example.com and vice-versa.

You could just use some javascript to get the URL based on the current document location, or use relative paths instead.

Also make sure the webserver isn't doing a silent redirect from one domain to another as this may also cause permissions issues.

The alternative if you have access to the webserver is to add the appropriate cross domain headers to the response - http://www.w3.org/TR/cors/

Example: Access-Control-Allow-Origin: http://www.example.com http://example.com

Edit: The domains in the above list need to be space separated, not comma.

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://sample.com http://www.sample.com"
</IfModule>

Upvotes: 4

epascarello
epascarello

Reputation: 207501

Subdomains are considered a different domain with the same origin policy. Use a relative path if you site functions with or without www.

If the server redirects, why is the current page not on www?

From a SEO standpoint, you probably want the server to do the redirects to one version of the url or the other.

Upvotes: 2

Related Questions