1

I'm trying to show either an image or static map image depends on existence of the image. I want to pass my image path to java script function since the path is dynamic in my program. So, if the image does not exist in given path, show the static google map image.
I am using that code to do that, but seems to be not working. Can you help me?

      function initialize() {
        var img = document.getElementById("super");
        var mdata = $('#image_div');
        var mpath = mdata .data('path');
        img.src =mpath ;

        img.onerror = function( ) {
        document.getElementById("super").style.display = "block";
        alert("failed to load");
    }
    img.onload = function( ) {
        alert("do nothing");
    };
}

Here is the fiddle: http://jsfiddle.net/H2gwu/2/ http://jsfiddle.net/H2gwu/3/

2 Answers 2

2

Fixed fiddle : http://jsfiddle.net/HCC6V/

Some errors I fixed :

  • a space after mdata
  • you opened a function block you never closed
  • you declared the src too soon : you may miss the load event if the image is in cache
  • bad quotes around none in the CSS
  • no call to show the map if image not found

Fixed JS :

var img = document.getElementById("super");
var mdata = $('#image_div');
var mpath = mdata.data('path');
img.onload = function( ) {
    alert("do nothing");
}
img.onerror = function( ) {
    document.getElementById("super").style.display = "block";
    alert("failed to load");
    $('#google_map').show();
}
img.src =mpath ;

In the CSS :

display: none;

instead of

display: "none";
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I do not want to show both,though. The default the image should be displayed, else the map. Can you please update your code to do that ?
@JohnSmith See edit. But you should try to test after each line you write until you get the feeling of this. That was much too many small errors.
0

For images that might exist i find most elegant solution is useing $ajax, like:

$.ajax({
    url: 'your_image.jpg',
    type: "POST",
    dataType: "image",
    success: function() {
        /* function if image exists (setting it in div or smthg.)*/
    },
    error: function(){
       /* function if image doesn't exist like hideing div or setting default image*/
    } 

});

1 Comment

Using POST can have weird side effects, depending on one's setup. For instance, if you're fetching images via a rest interface, using POST can effectively wipe out that image. That's because POST is not idempotent and it is not "safe". GET is "safe". See here. Also, beyond that, POST shouldn't be cached, so you end up with a more heavy handed solution when it's a repeatedly visited page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.