Thursday, 30 August 2012

How do check if file or image url exists using jQuery or Javascript json js ajax


Approach 1: (If its any file with any extension) :

To check whether files exist in file system, the best way to do this is with an AJAX HEAD request. HEAD requests only ask for and return the header from the destination file, so they’re much faster than POST or GET requests. Perfect for a simple file check.
It’s also returns the content length and last modified date and that jQuery has an “ifModified” option for the .ajax function that returns a Boolean value.
This jquery / javascript /js will be useful to check the image / file existence by providing source complete URL path  or relative URL path

Sample Demo Code

$.ajax({
    url:images/header.jpg',
    type:'HEAD',
    error:
        function(){
            alert(‘no File exist);
        },
    success:
        function(){
            alert(‘File exist’);        }
});

Approach 2 : (If its Image File with its related extension.)

The above approach is most recommended since this approach is not that much reliable and performance when compared to it to check existence.

HTML Source:
<img id=”image_id” src=” images/header.jpg” alt=”” />

JQuery:

This Jquery js will get call automatically when image is not available / loaded 
from file system or repository or directory.
 
$('#image_id').error(function() {

  alert('Image does not exist !!');

});
 

No comments:

Post a Comment