1

I have a script in php to create a graph (with jpgraph) and I use javascript to set that image in my page:

$("#page_image").attr('src', "generate_graph.php");

Sometimes my server doesn't work and I got a green image telling me the error and others I got just a crash icon image (not image found or so).

Is it possible to set a timeout and if after some seconds I got nothing, set a backup image already created?

Or, must I do it in php server side?

2
  • possible duplicate of Fallback for 404 images Commented Apr 18, 2015 at 14:25
  • What about using onerror html attribute? Commented Apr 18, 2015 at 14:28

2 Answers 2

1

Simple use .load() with setTimeout()

$(function(){

  var imageLoadTimeout = 1000; // millisecs
  
  // Timeout, if image not loaded in imageLoadTimeout time then we display error.jpg
  var timeout = setTimeout(function(){
     $("#page_image").attr("src", "error.jpg");
  }, imageLoadTimeout);
  
  
  $("#page_image").load(function(){
    clearTimeout(timeout);  // if image loaded sucessfully, clear the timeout
  });
  
  $("#page_image").attr("src", "generate_graph.php"); // Try to load image
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="page_image" />

Sign up to request clarification or add additional context in comments.

Comments

0

You can try error event:

$("#page_image").attr('src', "generate_graph.php").on('error', function() {
   $(this).attr('src', 'defaultimage.png');
});

Comments

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.