sckott sckott - 3 years ago 197
HTML Question

HTTP POST call embedded in a static html page

I want to embed an HTTP call which returns a png image into an html page.

I will run the page on github's gh-pages if that makes a difference.

The url is: http://public.opencpu.org/R/user/SChamberlain/ropensci_dash/apistatus10/png

Note that sometimes the url doesn't return the png as the service is sometimes down.

I want to call that url using POST method, and simply return the png into the page. Ideally the http call would be run on page recycle as well.

Do I use an iframe, form, javascript?

Thanks! Scott

Answer Source

[I might as well answer properly]

When a server is feeding you image data and you want to load it, you might as well treat it like an image and use an img tag. The problem with this approach in your particular case is that you said that the server can sometimes be down and this would mean that if you simply appended the image without checking for a broken link first you will get that ugly broken image space.

However, the simplicity of using an image is still feasible. By using a little javascript with a load event handler you can append the image if and only if it loads successfully. If you get any kind of error code from the request the load event will never fire and you won't append a broken image.

Here's the concept in vanilla-js:

img = document.createElement("img");
img.onload = function(e){document.getElementsByTagName("body")[0].appendChild(img);};
img.src = "http://public.opencpu.org/R/user/SChamberlain/ropensci_dash/apistatus10/png";

You can also see it in action here: http://jsfiddle.net/BwJeC/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download