Reputation: 507
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>
Upvotes: 0
Views: 189
Reputation: 1075337
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.)
Upvotes: 1
Reputation: 29025
var img = new Image();
img.onload = function () {
$("#imageContainer").append(img);
});
img.src ='~/temp/' + @ViewData["CaputredImage"] ;
Upvotes: 0