SiddP SiddP - 1 month ago 13
jQuery Question

Loading alternate image in sap.ui.commons.Image

new sap.ui.commons.Image({src: "http://localhost:9090/images/some-image.jpg"});


Suppose the above fails if http returns 404 or some error. The problem is the request is sent by Openui5 internally so it is not possible to intercept from server side either .In that case is there any way to give an alternate src such as below:

redirect url in case of http error -
src:"http://localhost:8080/images/no-image.png"


I have been trying the below but its not giving the result:

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
$.ajax({
// Resend the req
url: "http://localhost:8080/images/no-image.png"
});
//imageFile.setSrc("http://localhost:9090/images/no-image.png");
});

Answer

I have found a solution using formatter function for the source path received:

new sap.ui.commons.Image({src: {path : 'itemImg',formatter: function(itemImg){
        var ImageObject = new Image();
        ImageObject.src = itemImg;
        if(ImageObject.height>0){
        //alert("Ping worked!");
        return itemImg;
        }else {
        //alert("Ping failed :(");
        return "http://localhost:9090/images/no-image.png";
        }
    }}}).addStyleClass("itemImg"),