How to detect if image URL doesn't work - javascript

I got a javascript problem. I'm building a website which communicates with a MovieDB-API which will sometimes return broken URLs.
Is there any way to detect whether the URL returned by the API is going to lead to an empty page? Perhaps by checking retroactively if the image defaulted to the "alt"-attribute? Obviously, since the alt-text is showing, the program is "aware" of the fact that the URL fails.
In case the URL is broken, I want to have the IMG-variable replaced by the path to a local default-image.

CSS with javascript enabled
<img src="image.jpg" onerror="this.src='alternative.jpg';">
OR
jquery
// Replace source
$('img').error(function(){
$(this).attr('src', 'missing.png');
});
// Or, hide them
$("img").error(function(){
$(this).hide();
});
Edit
$(document).ready(function () {
$('img').error(function () {
$(this).addClass('noImg');
});
});
.noImg {
position: relative;
background: url() no-repeat center center; // or simple background color
height: 100px;
width: 100px;
content: "Your content";
margin: 0 10px 10px 0;
}

You can use the onerror event to check the URL and see if the image can be loaded.
var url = 'http://www.somesite.com/image.jpg';
var img = new Image();
img.onerror = function() {
console.log('image could not be loaded, setting default placeholder');
image_tag.src = '/my_default_placeholder.gif';
}
img.src = url;
without any posted code, it's just a general example of how it would work,

You could try to do an Ajax request for every image. If it does exist it will return success. Otherwise it throw an error and you can put the desired image in this place.
jQuery Ajax snippet:
$.ajax({
type: "GET",
url: url_to_img,
success: function(result) {
console.log("SUCCESS");
$('#img-1234').attr('src', url);
},
error: function(result) {
console.log("ERROR");
// url broken
$('#img-1234').attr('src', '/img/noImg.png');
}
});
Hope it helps

Related

AJAX Complete Handler not beeing fired

After some hard work on the backend of my Web Application I noticed that the GetMeasure Request takes up to 10 seconds to finish. I decided to apply an overlay so a potential user won't get confused because nothing happens on the screen. No matter if the request is successfull or not the overlay should get removed after the call - so using the complete handler should be the best choice - at least I thought. I really don't get why but in opposite to the success handler the complete handler won't get called.
AJAX Request:
$_loadingCircle = $('<img id="loading" src="http://www.obergurgl.com/_images/layout/loading.gif"/>');
PopulateOverlay($_loadingCircle);
$.ajax({
url: 'CoDTracker/Home/GetMeasures',
type: 'POST',
dataType: "html",
data: {
buID: buid,
aID: aid,
lID: lid
},
success: function (data) {
$('#measures').html(data);
},
complete: function () {
$_overlay.remove();
}
});
The request ends with status 200 (successfull) but the overlay won't get removed. I'm sure that the request completed because my measures got filled into the page while the circle spins as crazy instead of disappearing.
Am I doing something wrong?
Edit:
Overlay-definition
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
Your $_overlay is defined incorrectly.
Please use:
$_overlay = $('div.overlay');
And please refer to jQuery Selectors for more information:
https://api.jquery.com/category/selectors/
The way to select a div with a particular class, is not to copy the entire <div class="">, but rather as I did in the example above.
EDIT: in fact, if you make this change, your PopulateOverlay will no longer work, so you should rather just select it without assigning it to a variable:
complete: function () {
$('div.overlay').remove();
}
Because overlay is appended in the DOM, you should remove it with .class:
complete: function () {
$('.overlay').remove();
}
First, if there's no error, and that's all your code, it should work fine.
Let's try to make an example, with a mimic function to mimic the behavior of ajax complete, we can write it like:
var $_overlay = null; // We assume you define it somewhere, and it's visible to all your functions.
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
mimic(function() {
$_overlay.remove();
});
}
$(function() {
theWorks();
});
.overlay {
display: block;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So I guess, that your codes, is inside another function, and you may call it many times, let's make a button, and click to trigger it:
var $_overlay = null; // We assume you define it somewhere, and it's visible to all your functions.
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
mimic(function() {
debugger;
$_overlay.remove();
});
}
$(function() {
$('#click').on('click', theWorks);
});
.overlay {
display: block;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
Now, if click the button before the previous pop out disappear, some popouts last forever.
Why? Because when you click again, your $_overlay will be assign to a newly created element, which means you lost the reference to the previous pop out, and when later the remove works takes action, it only remove the newest one, and all the following removes, are about to remove something that is not on the page, so you won't see effects, and older popouts remains.
We could fix it, by catch the current element in another variable when you're executing your codes. This would work if you expect many pop outs.
var $_overlay = null; // We assume you define it somewhere, and it's visible to all your functions.
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
// Cache the current overlay, or simply move $_overlay here, if no other using it.
var $_curOverlay = $_overlay;
mimic(function() {
$_curOverlay.remove();
});
}
$(function() {
$('#click').on('click', theWorks);
});
.overlay {
display: block;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
Or as what Laurens Swart suggest, simply toggle the state if you only need one pop out at a time.
var $_overlay = $('.overlay');
function PopulateOverlay($content) {
$_overlay
.empty() // Clear previous
.append($content) // Append the content
.show(); // Make it visible.
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
mimic(function() {
$_overlay.hide(); // Instead of remove, we make it hide, so we can reuse it later.
});
}
$(function() {
$('#click').on('click', theWorks);
});
.overlay {
display: none;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
<div class="overlay"></div>

How To Call Function on page Loading

I'm Using Web service using AJAX Call In My HTML Page . Web Service Returning Data Nearly 30 to 40 second's .
During This Loading Time I Need to Use Some Loading Gif Images After Data Completely Received Form Web Service The Loading Image Must Be Hide.
I'm Using Only HTML,JAVASCRIPT,CSS,J Query.
Any Idea Or Samples Needed.
I'm Using Following Code
$(document).ready(function () {
document.write('<img src="http://www.esta.org.uk/spinner.gif">');
});
$( window ).load(function() {
//This following Function Related To My Design
jQuery(".chosen").data("placeholder", "Select Frameworks...").chosen();
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
});
In The Above Code My Problem Is On Page Load Gif Image Show But It's Not Hide Only Gif Image Only Showing.
Put a hidden image on your page and as soon as your ajax call is made, make that image visible
$('#image').show();
$.ajax({
complete: function(){
$('#image').hide();
}
});
and hide that image again on Complete of Ajax call.
Use your ajax request callback (on success/failure) instead of page load.
When sending the request just show a gif animation by setting the Display to block
then when you have the data set the display to none
or use jquery
function showHourGlass()
{
$("#gifimage").show();
}
function hideHourGlass()
{
$("#gifimage").hide();
}
You ask for ideas, I have one sample -
http://www.myntra.com/shoes
load scroll down fastly this is the ajax jquery request which is exact output which you have mentioned in your question
Check source code
Jquery Ajax loading image while getting the data
This what the html looks like:
<button id="save">Load User</button>
<div id="loading"></div>
and the javascript:
$('#save').click(function () {
// add loading image to div
$('#loading').html('<img src="http://preloaders.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
// run ajax request
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.github.com/users/jveldboom",
success: function (d) {
// replace div's content with returned data
// $('#loading').html('<img src="'+d.avatar_url+'"><br>'+d.login);
// setTimeout added to show loading
setTimeout(function () {
$('#loading').html('<img src="' + d.avatar_url + '"><br>' + d.login);
}, 2000);
}
});
});
I hope this will help you.

Load image after json respond

How can I load an image after successful json respond?
jQuery
$.post('#Url.Action("Upload", "Camera")', {
type: 'data',
image: canvas.toDataURL("image/png")
}, function (result) {
if(result.success) {
alert('The image was successfully sent to the server for processing');
var $image = $("<img src='~/temp/" + #ViewData["CaputredImage"] + "'/>");
$image.live("load", function () {
$("#imageContainer").append(this);
});
}
});
Image container
<div id="imageContainer"></div>
I'd probably include the path to the newly-submitted image in the JSON sent back from the server, and then:
$.post('#Url.Action("Upload", "Camera")', {
type: 'data',
image: canvas.toDataURL("image/png")
}, function (result) {
if(result.success) {
alert('The image was successfully sent to the server for processing');
// *** Change is on next line ***
var $image = $("<img src='" + result.imagePath + "'/>");
// *** Another change on the next line ***
$image.on("load", function () {
$("#imageContainer").append(this);
});
}
});
Also note I changed the live call to on. That wasn't the correctly way to use live in the first place, and secondly it's been deprecated for a while and has now actually been removed.
Separately, you have a race condition there (although in this case, one that's very unlikely to actually cause you a problem): You aren't hooking the load event of the image until after you've specified its src. Although JavaScript on browsers is single-threaded (unless you use web workers), the browser is not. If it already has the image in cache (again, unlikely in this case), it can fire the load event before you hook it — and seeing no handlers attached to the event, it doesn't queue them to run when the JavaScript is next idle.
Also (at the other extreme), you're waiting to add the image to the document until after it's loaded; I'm not 100% certain all browsers will load the image if it's not in any document.
So for what it's worth:
$.post('#Url.Action("Upload", "Camera")', {
type: 'data',
image: canvas.toDataURL("image/png")
}, function (result) {
if(result.success) {
alert('The image was successfully sent to the server for processing');
// *** Changes start here ***
var $image = $("<img>");
$image.css({
position: "absolute",
left: -10000,
top: 0
});
$image.attr("src", image.imagePath);
$image.appendTo(document.body);
$image.on("load", function () {
$image.remove();
$("#imageContainer").append("<img src='" + result.imagePath + "'>");
});
// *** End of changes ***
}
});
That creates an img element off-page but in the document, hooks image load, sets the src, and on load drops that img element in favor of a newly-created one that doesn't have the CSS applied to it. (You can chain those calls together, kept them separated for clarity.)
var img = new Image();
img.onload = function () {
$("#imageContainer").append(img);
});
img.src ='~/temp/' + #ViewData["CaputredImage"] ;

optimizing colorbox and adding extra jquery

I have two problems
I am trying to open a jQuery colorbox and it is very slow. The reason is I am trying to get html content from a different page (I cannot use iframe because I just need a part of this page). The following code works but it takes time after the button is clicked:
$(document).ready(function() {
$(".cart-link a").click(function(event) {
$(this).colorbox.close();
});
$(".rest-menuitem a").click(function(event) {
event.preventDefault();
var result = null;
var sURL = $(this).attr("href");
$.colorbox({
html: function() {
$.ajax({
url: sURL,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return $(result).find('.product');
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
});
});
I want to know if there is a alternative way to do it. I dont mind if the colorbox popup and then takes time to load the content. The above version can be fount at this url (http://delivery3.water-7.com/index.php/restaurants/manufacturers/3/Barcelona-Restaurant-&-Winebar/products).
I am also trying to close the colorbox when a user clicks on add to cart. But some reason it is not triggered. $(".cart-link a").click is not triggered when I click on add to cart. Is there a special way to add jquery to colorbox content?
Try this instead:
$(".rest-menuitem a").colorbox({
href: function(){
return $(this).attr('href') + ' .products';
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
ColorBox uses jQuery's load() method for it's ajax handling, so you just need to add the desired selector to the link's href.
For your question 2 can you try this ?
$(document).ready(function() {
$(".cart-link a").live('click',function(event) {
$(this).colorbox.close();
});
});
For your question 1..it will be slow since you are fetching it from different page.Use a different logic for that
For your question no 1
$('selector').colorbox({onLoad: function() { /*Intially load a empty color box with only <div id="contenttoload"></div> (No other html content */
$.ajax({
url :'Your url',
data : {}, //data to send if any
type : "POST" //or get
success:function(data){ /*data means the stuff you want to show in color box which you must return from the other page*/
$('#contenttoload').html(data); //data should be well formatted i mean add your css,classes etc from the server itself */
}
});
}});

Show AJAX content after images have loaded

I am developing my own lightbox kind of jquery plugin. Everything works but I want to hide the loaded content until the images have loaded in the browser from the AJAX call. I found a similar post and I am using the following script but the setTimeout function is what reveals the content and not the .load function. Am I trying to achieve the impossible?
$.ajax({
url: 'meet/'+ pLoad + '.html',
success: function(data) {
var imageCount = $(data).filter('img').length;
var imagesLoaded = 0;
$(data).hide()
.appendTo('#zoom_inner')
.filter('img')
.load( function() {
++imagesLoaded;
if (imagesLoaded >= imageCount) {
$('#zoom_inner').children().show();
}
});
setTimeout( function() { $('#zoom_inner').children().show() }, 5000 );
}
});
Regarding your comments:
data is just a string in your success callback - it's "html", but it's a string.
make it a node to use:
var $images = $(data); // i.e. turn <div><img /></div> into a div with an img as a child or whatever you got
var imageCount = $images.find('img').length;
cool, eh?
If you investigate this article I think you can find solution for your problem (http://jqueryfordesigners.com/image-loading/)
Best wishes.

Categories

Resources