XMLHttpRequest and subdomains

If you’re trying to do a XMLHttpRequest in JavaScript but keep failing, this might help you:

First, you need to know two important things:

  1. If you try to call a file using the XMLHttpRequest object in JavaScript, which is located on a different server, relative to the running JavaScript source, you’ll probably get an error.
    The simple reason for this is, that many servers don’t allow crossdomain http-requests.
  2. If both files, the JavaScript source, and the file to parse, are on the same server, using the same domain, you should be safe.

Now, here comes the nasty problem.

Let’s assume, we have a JavaScript file called test.js, which is located at http://www.mydomain.com/test.js.

Further, we have a test file, which we want to load though our Ajax call, which is located at http://www.mydomain.com/test.xml.

Now try to do the Ajax call like this:

var req = new XMLHttpRequest();
req.open("GET", "http://www.mydomain.com/test.xml", false);
req.overrideMimeType("text/plain");
req.setRequestHeader('Content-Type', 'text/plain');
req.onload = function(){
alert("Ajax call was successful");
};
req.send(null);

Open the JavaScript file http://mydomain.com/test.js in your browser.

You’ll notice that this won’t work. Why is that so?

The reason is simply, that we forgot to type “www” in the browser: http://www.mydomain.com/test.js.

Remember that “www” is just a subdomain, nothing more, but enough to change the domain name so that our Ajax call won’t work. In many browsers, you can just type cnn.com instead of www.cnn.com and it’ll work fine as long as you just want to surf the web, but if you’re doing Ajax calls you’ll really have to be careful. Might save you a lot of time and nerves :-)

Follow me on social media

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.