Return to Snippet

Revision: 953
at August 23, 2006 02:28 by pablazo


Initial Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Using AJAX to check if a file exists</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<script type="text/javascript">
var req, image, warning, imagepath;

function d(o)
{
	return document.getElementById(o);
}

function loadimage(_imagepath)
{
	image = d("image");
	image.style.display = "none";

	imagepath = _imagepath;

	warning = d("warning");
	warning.innerHTML = "Loading ...";

	req = getreq();
	req.onreadystatechange = imagexists;
	req.open("get", imagepath, true);
	req.send(null);		
}

function imagexists()
{
	if(req.readyState == 4)
	{
		if(req.status == 200)
		{
			warning.innerHTML = "Image exists";
			image.style.display = "block";
			image.src = imagepath;
		}
		else
		{
			warning.innerHTML = "Image does not exist";
			image.style.display = "none";
		}
	}
}

function getreq()
{
	if(window.XMLHttpRequest)
		return new XMLHttpRequest();
	else if(window.ActiveXObject)
		return new ActiveXObject("Microsoft.XMLHTTP");
}

</script>
<style type="text/css">
* { font-family: Verdana, Arial, sans-serif; }
body { background-color: #FFF; }
h1 { font-size: 14px; }
#warning { margin: 10px; }
#img { border: 1px solid #CCC; padding: 3px; margin: 10px; }
</style>
</head>

<body>

	<h1>Check an image exists with AJAX</h1>

	<input type="button" value="Load real image" onclick="loadimage('IMAG0272.jpg');" />
	<input type="button" value="Load fake image" onclick="loadimage('5hhhh_thumb.jpg');" />

	<div id="warning"></div>
	<img id="image" src="blank.jpg" style="display: none;" alt="" />

</body>
</html>

Initial URL
http://www.moddedup.com/imageexists/imageexists.html

Initial Description


Initial Title
check an image exists with ajax

Initial Tags
ajax, image

Initial Language
JavaScript