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"] ;
Related
I've been searching for a solution but all i'm getting is $(window).on("load", fuction(){}) which just loads the html resources.
I'm creating a variable amount of images and inserting them in a div with jquery using an each() function after the window is loaded.
$.each(footeradds, function(fad){
$("<div class=\"footerads\"><img src=\"image" + fad + ".jpg\"/></div>").appendTo(".footer");
});
I need to calculate the width of the container of these images which depends on the amount of images and their width, which they only have after they've loaded.
if i do
$(".footer img").on("load", function() {})
that function is called every time an image loads, and need it to only be called once, after ALL images have loaded.
My question is: how can i invoke a function after images created with jquery are loaded?
there is no methods for it but you can do one thing
take a variable A = count all images , then create other variable B = 1 and increment it on every image load and
check condition A == B
that condition will true when last image will called .....:)
Turn the event off after first time
$(".footer img").on("load", function() {
$( this ).off( event );
})
So i ended up using Pratik Bhalodiya's idea and made this:
var footerW = 0;
var fimgs = 0;
$(".footer img").on('load', function() {
footerW += + $(this).width();
fimgs++;
if (fimgs == $(".footerads").length){
//do stuff here
}
});
thanks for your help everyone!
You could just use a deferred for each image, and $.when to check that all are resolved etc
var p = $.map(footeradds, function(fad){
var def = new $.Deferred,
div = $('<div />', {
'class' : 'footerads'
}),
img = $('<img />', {
on : {
load : function() {
def.resolve(this);
}
},
src : 'image' + fad + '.jpg'
});
$(".footer").append( div.append(img) );
return def.promise();
});
$.when.apply($, p).then(function(images) {
// all images loaded
var images = [].slice.call(arguments);
// use images here
});
I need to load video source, multiple types, from another website, which on get returns text link into video.
For example i open:
http://www.getthisvideoexample.com?whichvideo=id0
it shows in web browser text link:
http://someotherserver.com/somesubdomainrandomuniquenumber/thisisyourvideovalidforsometime.mp4
or
http://www.getthisvideoexample.com?whichvideo=id0&webm=true
and it shows in web browser text link:
http://someotherserver.com/somesubdomainrandomuniquenumber/thisisyourvideovalidforsometime.webm
But this server sometimes, when load is high,returns 500 error.
So i need to handle it all.
Lets take for example:
<video id="myVideo"></video>
var player = new MediaElementPlayer('#myVideo', {
type: ['video/mp4', 'video/webm'],
success: function (mediaElement, domObject) {
var sources = [
{ src: "HOW_TO_PUT_HERE_DYNAMICALLY_LOADED_MP4_LINK?", type: 'video/mp4' },
{ src: "HOW_TO_PUT_HERE_DYNAMICALLY_LOADED_WEBM_LINK?", type: 'video/webm' }
];
mediaElement.setSrc(sources);
mediaElement.load();
mediaElement.play();
}
});
Also how to make it so, that if 500 or other error is returned instead of link to video, code will just wait few seconds and try again, or display message with text "trying again, wait...."?
Thanks.
I would try a different approach.
I would place an ajax request (using jQuery.ajax()) within a setInterval loop (every 2 seconds perhaps). If the AJAX request, either
http://www.getthisvideoexample.com?whichvideo=id0 // returns a MP4 file
... or
http://www.getthisvideoexample.com?whichvideo=id0&webm=true // returns a webm file
... is successful, then clear the interval (clearInterval()), otherwise keep trying until the server responds successfully (you may need to set a method to clear the interval after some time in case the server is not available, otherwise you will end up in an infinity loop)
How-to?
If the ajax request is successful, then I would build the <video> tag structure with the response and append the tag to a video container (a <div> perhaps)
Then I would bind MEJS to the selector of the newly appended tag like :
var URL = "http://www.getthisvideoexample.com?whichvideo=id0 "; // request video URL
jQuery(document).ready(function ($) {
var getVideo = setInterval(function () {
$.ajax({
url: URL,
cache: false,
dataType: "json", // or else
success: function (response) {
clearInterval(getVideo); // ends loop
// build video tag
// select proper type, based on response
var video = '<video id="video_player" width="320" height="240" controls>' +
'<source src="' + response + '" type="video/' + (response.indexOf("webm") == -1 ? 'mp4' : 'webm') + '" />' +
'</video>';
// target container's selector
$("#videoContainer")
.html(video) // insert video tag
.find("#video_player") // find video selector after insertion
// bind MEJS
.mediaelementplayer({
// MEJS options
});
},
error: function () {
// error in ajax, will try again in 2 seconds
}
});
}, 2000);
}); // ready
I'm using a file uploader called "upload-at-click" from: https://code.google.com/p/upload-at-click/
It works good but the problem I'm having is I need two upload buttons on the page to upload two separate kinds of files. But I can only have one instance of the upclick() function, so I'm not sure how I can do this?
The code used for one button is:
var element = document.createElement('input');
element.value = 'Load CSV';
element.id = 'uploader';
element.type = 'button';
stage.appendChild(element);
upclick({
element: element,
action: '/mailer/file_upload.php',
onstart: function (filename) {
alert('Uploading: ' + filename);
},
oncomplete: function (response_data) {
alert('Data upload complete.');
}
});
I think you can pass element as already existing element from DOM.
$('.uploadButton').click(function(){
upclick({
element : this // or maybe jQuery object $(this) ???
/* rest of code */
});
});
I have a simple question but I couldn't find a clean answer. I need to load heavy images after an ajax call and I want to use an animated gif as a pre-loader. I'm using the follow code:
function loadProducts(url) {
$("#loading").show();
$('#inner').fadeOut(1).load(url + ' .product-list', function() {
$('#inner').fadeIn(1000, function() {
$("#loading").hide();
});
});
}
The #loading is hiding when the HTML is loaded .load(url + ' .product-list'. The problem is that the heavy images are still rendering on the screen and I would like to keep showing the animated .gif until the renders of the images are finished. Is there a way to know when the images on the screen are rendered?.
Thanks in advance.
You can use promises to check when all the images have loaded, and then remove the loading gif.
This creates a promise that is resolved when the image has loaded, all the promises are kept in an array, and when all promises are resolved, i.e. all images are loaded, the callback fires.
function loadProducts(url) {
$("#loading").show();
$('#inner').fadeOut(1).load(url + ' .product-list', function() {
var promises = [];
$('#inner').find('img').each(function(_, image) {
var img = new Image(),
def = new $.Deferred();
img.onload = function() {
def.resolve();
}
promises.push( def.promise() );
img.src = image.src;
if (img.complete) img.onload();
});
$.when.apply(undefined, promises).done(function() {
$('#inner').fadeIn(1000, function() {
$("#loading").hide();
});
});
});
}
You can use ImagesLoaded
Sample usage
imagesLoaded( document.querySelector('#container'), function( instance ) {
console.log('all images are loaded');
});
// selector string
imagesLoaded( '#container', function() {...});
// multiple elements
var posts = document.querySelectorAll('.post');
imagesLoaded( posts, function() {...});
Could add/remove the loader as a class? I have base 64encoded the loader, so there is no pre loader required. This also uses a closure to allow the counter to remember its value.
var imgDiv = document.getElementById("imgDiv");
imgDiv.onclick = (function () {
"use strict";
var count = 0; // init the count to 0
return function () {
count++; //count
if (count === 1) { // do something on first click
$('.img-loader-content').addClass('loader');
$('.imgDiv').load("images/img.jpg", function () {
$('.img-loader-content').removeClass('loader');
});
}
if (count > 1) {
$('.imgDiv').slideToggle(400);
}
};
})
();
You may try using Image object. E.g:
function loadImage(url) {
$("#loading").show();
var img = new Image();
img.src = url;
img.onload = function(e) {
$("#loading").hide();
//ur code to append/show the image
};
}
the most approach to this is using onLoad , so basically after the success call of ajax , invoke another call into success function :
http://www.w3schools.com/jsref/event_onload.asp
onload is most often used within the element to execute a
script once a web page has completely loaded all content (including
images, script files, CSS files, etc.).
or use native solution like this :
<img src="w3javascript.gif" onload="loadImage()">
http://www.w3schools.com/jsref/event_img_onload.asp
Also last answer of this question is very useful in your case :
Is there something similar to `$(window).load();` for executing a function after newly inserted Ajax content has finished loading?
You can do it easily by ajaxComplete callback, here check an example http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_ajaxcomplete
I've been trying to figure out this semi-specific problem for the past couple days, and I could really use another pair of eyes on it.
My goal is to have an image on the page. It starts out as a static png, and when it's clicked, it swaps out with a .gif and plays an animation. When it's click on again, it swaps again and plays a second .gif animation. It does the same thing a third time. When the 3rd .gif is clicked on, it plays the 1st gif animation again, and the process starts all over again.
My issue is that multiple images are loaded on the page, and some have 3 total gif animations, some have 2, and some have one.
So what I'm trying to do is check if the .gifs exist before I load the next one.
Here's an excerpt with some of my notation...
$('#postContainer img').click(function () {
imgSrc = $(this).attr('src');
if(imgSrc.indexOf('_B.png') != -1){
imgSrcToUse = imgSrc.replace('_B.png', '_pt1.gif');
$(this).attr('src', imgSrcToUse);
return false;
}
That code above runs when the image is clicked. It finds the image src, and replace the static png with the first animated gif. all the images have an animated gif, so this isn't a problem.
if (imgSrc.indexOf('_pt1.gif') != -1) {
var POS2 = imgSrc.replace('_pt1.gif', '_pt2.gif');
$.ajax({
url: POS2,
type: 'HEAD',
error: function() {
alert('error');
imgSrcToUse = imgSrc.replace('_pt1.gif', '_pt1.gif');
},
success: function() {
alert('success');
imgSrcToUse = imgSrc.replace('_pt1.gif', '_pt2.gif');
}
});
$(this).attr('src', imgSrcToUse);
return false;
}
After _pt1 is loaded, then this function runs the next time you click. it is supposed to check if a _pt2 exists, and if it does, then swap out the pt1 with pt2. HOWEVER, it only seems to be working on the second click. if i click it once, it loads _pt1 again, and then the second time through it will load _pt2 properly. this is where my major problem lies...
i apologize if this is convoluted but i'm really stumped here. i'll try to do my best to clear things up if you guys are way too confused.
Here is your issue:
$.ajax({
url:POS2,
type:'HEAD',
error: function()
{
alert('error');
imgSrcToUse = imgSrc.replace('_pt1.gif','_pt1.gif');
},
success: function()
{
alert('success');
imgSrcToUse = imgSrc.replace('_pt1.gif','_pt2.gif');
}
});
$(this).attr('src',imgSrcToUse);
That last line of code is trying to use your variable imgSrcToUse, which doesn't contain the result of your AJAX query yet. AJAX is asynchronous, so your $.ajax call returns and moves onto the next line before the success (or error) callbacks are called. You can resolve this by moving the code using the data from the callbacks into the callbacks:
var $that = $(this);
$.ajax({
url: POS2,
type: 'HEAD',
error: function () {
alert('error');
var imgSrcToUse = imgSrc.replace('_pt1.gif', '_pt1.gif');
$that.attr('src', imgSrcToUse);
},
success: function () {
alert('success');
var imgSrcToUse = imgSrc.replace('_pt1.gif', '_pt2.gif');
$that.attr('src', imgSrcToUse);
}
});
You were seeing sucess on the second call because you were assigning the next image name to a global variable. You should use var to avoid this.