Skip to content

Instantly share code, notes, and snippets.

@vdite
Last active July 20, 2018 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdite/11369781 to your computer and use it in GitHub Desktop.
Save vdite/11369781 to your computer and use it in GitHub Desktop.
jQuery: how to check if file exists
var base='http://mizine.de';
var url='/image_path_to_test.jpg';
var fallback_url='/image_path_exists_for_fallback_image.jpg';
/** Asynchronous!!! **/
$.get(base+url).done(function(){
$('#any_DOM_id').append('<img id="my_image" src="'+url+'"/>');
}).fail(function(){
$('#any_DOM_id').append('<img id="my_image" src="'+fallback_url+'"/>');
});
@vdite
Copy link
Author

vdite commented Apr 28, 2014

Hint: $.get() is asynchronous, so this way 'll kill the sequential chronology of your script execution

@arageshashi
Copy link

$.get is not working if images are protected.

Giving below exception
'http://localhost:49178' is therefore not allowed access.
XMLHttpRequest cannot load http://XXXXXXXX/18c5f608-ff4f-46ff-8d09-5ae2fd517624.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49178' is therefore not allowed access.
XMLHttpRequest cannot load

But below code is working for above case.
$('').load(function() {
return true;
}).bind('error', function() {
return false;
});

@jashirouprotips
Copy link

Hey, I was searching something like this and I found it, thanks hehehe.

This is my code, I was trying to place in drupal custom view-template a file reader and validate if the image exist or not, in php is easy to read a directory but twig doesn't have this function, but fortunatly you have the way I was searching at las resource.

This is my code:

                        jQuery(document).ready(function () {
                                var base='/sites/images/anuarios-portadas';
                                var url='/{{ portada_image }}';
                                var fallback_url='/no-portada.png';

                                /** Asynchronous!!! **/
                                jQuery.get(base+url).done(function(){
                                    jQuery('#portada_{{ portada }}').append('<img id="portada_img_{{ portada }}" class="img-responsive" src="'+base+url+'"/>');
                                }).fail(function(){
                                  jQuery('#portada_{{ portada }}').append('<img id="noportada_img_{{ portada }}" class="img-responsive" src="'+base+fallback_url+'"/>');
                                });
                            });

Thanks for the Post...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment