We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

pablazo on 08/23/06


Tagged

ajax image


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

nutella
vali29


check an image exists with ajax


Published in: JavaScript 


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

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html>
  3. <head>
  4. <title>Using AJAX to check if a file exists</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
  6. <script type="text/javascript">
  7. var req, image, warning, imagepath;
  8.  
  9. function d(o)
  10. {
  11. return document.getElementById(o);
  12. }
  13.  
  14. function loadimage(_imagepath)
  15. {
  16. image = d("image");
  17. image.style.display = "none";
  18.  
  19. imagepath = _imagepath;
  20.  
  21. warning = d("warning");
  22. warning.innerHTML = "Loading ...";
  23.  
  24. req = getreq();
  25. req.onreadystatechange = imagexists;
  26. req.open("get", imagepath, true);
  27. req.send(null);
  28. }
  29.  
  30. function imagexists()
  31. {
  32. if(req.readyState == 4)
  33. {
  34. if(req.status == 200)
  35. {
  36. warning.innerHTML = "Image exists";
  37. image.style.display = "block";
  38. image.src = imagepath;
  39. }
  40. else
  41. {
  42. warning.innerHTML = "Image does not exist";
  43. image.style.display = "none";
  44. }
  45. }
  46. }
  47.  
  48. function getreq()
  49. {
  50. if(window.XMLHttpRequest)
  51. return new XMLHttpRequest();
  52. else if(window.ActiveXObject)
  53. return new ActiveXObject("Microsoft.XMLHTTP");
  54. }
  55.  
  56. </script>
  57. <style type="text/css">
  58. * { font-family: Verdana, Arial, sans-serif; }
  59. body { background-color: #FFF; }
  60. h1 { font-size: 14px; }
  61. #warning { margin: 10px; }
  62. #img { border: 1px solid #CCC; padding: 3px; margin: 10px; }
  63. </style>
  64. </head>
  65.  
  66. <body>
  67.  
  68. <h1>Check an image exists with AJAX</h1>
  69.  
  70. <input type="button" value="Load real image" onclick="loadimage('IMAG0272.jpg');" />
  71. <input type="button" value="Load fake image" onclick="loadimage('5hhhh_thumb.jpg');" />
  72.  
  73. <div id="warning"></div>
  74. <img id="image" src="blank.jpg" style="display: none;" alt="" />
  75.  
  76. </body>
  77. </html>

Report this snippet 

You need to login to post a comment.