I’m using this function to check if a webpage exists. To do this I am checking if it has a header. But I always get a 404, even with a blank url.. what am I doing wrong here?
var xmlhttp;
function checkURL(url){
xmlhttp=null; // initialize the request object
// All the browsers except for the old IE
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("HEAD",url,true)
xmlhttp.send(null)
}
// old IE
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
if (xmlhttp)
{
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("HEAD",url,true)
xmlhttp.send();
}
}
}
function xmlhttpChange()
{
// if loaded
if (xmlhttp.readyState==4)
{
// if head exists "OK"
if (xmlhttp.status==200)
{
alert('URL exists')
}
else
{
alert("Status is "+xmlhttp.status)
}
}
}
It works fine for any page that you are allowed to access.
Demo: http://jsfiddle.net/Guffa/dPMah/
You can only access pages in the same domain using the XMLHTTP object.