Skip to content

Instantly share code, notes, and snippets.

@vdite
Last active July 20, 2018 22:22
Show Gist options
  • 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+'"/>');
});
@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