I’m trying to parse and load an XML (from WordPress) from the same domain but I am getting the following error:
XMLHttpRequest cannot load http://www.knead-nyc.com/articles/feed/. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.
What’s strange is that my html page is located here:
http://knead-nyc.com/test.html
and my WordPress xml feed is here: http://www.knead-nyc.com/articles/feed/
My HTML code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
function parse(document){
$(document).find("item").each(function(){
$("#content").append(
'<br /> Title: '+$(this).find('title').text()+
'<br /> Author: '+$(this).find('link').text()+
'</p>'
);
});
};
$.ajax({
url: 'http://www.knead-nyc.com/articles/feed/', // name of file you want to parse
headers: {'X-Requested-With': 'XMLHttpRequest'},
dataType: "xml",
success: parse,
error: function(){alert("Error: Something went wrong");}
});
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
I installed WordPress in the “articles” folder. In order to prevent domain conflict I made the following changes to the .htaccess
file located in the WordPress root directory but it’s not working:
# BEGIN WordPress
<IfModule mod_rewrite.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true
RewriteEngine On
RewriteBase /articles/
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /articles/index.php [L]
</IfModule>
# END WordPress
I did a bit of searching and found a solution. Although I was on the same domain (example.com) I was getting the following error. “XMLHttpRequest cannot load http://example.org/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin http://www.example.org is therefore not allowed access”
I found out that occasionally, the same origin policy may block requests between sub-domains on the same domain. So after a few searches I was able to solve this problem by by adding document.domain within my JavaScript. For example:
document.domain = ‘example.com’;
I also changed the top portion of my JavaScript to: