Is the following code sufficient for the purposes of XHRing a remote server? The only thing changed from normal XHR code is that I put the full server URL into the URL parameter of the open method of the XHR object. I'm not sure if that's enough? It didn't work; so I'm not sure what's missing.
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://insertURLofRemoteServerHere.com?parameter1=true",true);
xmlhttp.send();
}
</script>
Normally, Javascript can only send xhrs to the server from which the javascript was loading. It's called the Same Origin Policy. I suspect that is what is stopping you.
You code seems correct for the most part. you're handling cross browser compatiblity etc. However, the Same Origin Policy will not allow you to receive a response from a script on a remote server.
A workaround for this would be if the remote server supports the JSON-P response format.
Another workaround is if the server supports Cross Origin Resource Sharing. However, from personal experience, this is spotty. I would go with JSON-P if the server supports it.
(Side note: You could make your life so much simpler if you used a library/framework like Jquery. The above code snippet could be condensed to 3-4 lines of code, and the framework will take care of cross-browser compatibility.)