Last active
July 20, 2018 22:22
-
-
Save vdite/11369781 to your computer and use it in GitHub Desktop.
jQuery: how to check if file exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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+'"/>'); | |
}); |
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
$.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;
});