Reputation: 2263
How do I get hold of the response from a (non-ajax) image request.
Using jQuery I'm doing:
$('#myimg').error(function(err) {
console.error(err);
}
However this err object doesnt have the response sent from the server. I can view the error response in chrome dev tools.. and it is the expected response for this error, but how do I access that message from javascript/jquery?
Upvotes: 2
Views: 1690
Reputation: 5662
If you are referring to the HTTP response I don´t think you will be able to get that through Javascript. Explain what you are trying to achieve and there might be other solutions that suits your needs.
I created a small demo using the load and error events.
Javascript
$('img').load(function(e) {
// Image loaded
console.log(e.type, e);
})
.error(function(e) {
// Failed to load image
console.log(e.type, e);
$(this).addClass('error');
// NOTE: You could also change the src attribute.
});
CSS
img {
width: 200px;
height: 200px;
margin: 10px;
background: url('http://placekitten.com/g/200/200') no-repeat;
}
.error { border: 2px dashed red; }
HTML
<img id="img1" src="http://placekitten.com/200/200" />
<img id="img2" src="http://placekitten.com/no/such/file" />
Upvotes: 0
Reputation: 12705
i dont think there is a way to do that
what you can do instead is make an ajax call when ever error event is raised
$('img').error(function(err){
var src = $(this).attr('src');
$.ajax(src,[settings]);
})
$('img')[0].src = "http://asdasdasd.com";
and you will get the response in the error handler of the ajax
call
Upvotes: 2