How to update placeholder content with generated image in Rails?

I have a div tag in a view that I would like to update with a graph that I generate via Gruff.

I have the following controller action that does this at the end

send_data g.to_blob, :disposition=>'inline', :type=>'image/png', :filename=>'top_n.pdf'

      

Now if I call this action directly, I can see the graph. (More details here if reqd.)

If I add link_to_remote_tag

that calls the specified action via AJAX, going through a specific input, generates this graph and tries to update the placeholder div tag ... I see gibberish.

I think I can write a graph in a png file with g.write(filename.png)

how to insert a graph into a div tag in the view at runtime?

0


source to share


2 answers


Into your link_to_remote: tag, complete with something like this:

:complete => "updateImg(id_of_div, request.responseText)"

      

And write a JS function:



function updateImg(id, img)
{
  $(id).innerHTML = '<img src="' + img + '" />';
}

      

If id_of_div is the div id when you want to show the image.

The Request.responseText var comes from an AJAX call request, I mean when your code writes a png file with a graph, complete the method returning the path to that new png (render: text => path_to_new_image); then use that query variable in: complete.

+1


source


You can use a regular tag img

to invoke a controller action that returns the generated png. If you configured your controller to use reply_to something like this:

def graph
    # get the relevant data for 'g' here
    respond_to do |format|
        format.html #uses the default view if relevant (good for debugging)
        format.png do 
            send_data g.to_blob, 
                :disposition=>'inline', 
                :type=>'image/png', 
                :filename=>'top_n.pdf' 
        end
    end
end

      

You will even have a normal generator url:



<img src="controller/graph.png" alt="Something"/>

      

If there is a chance that image generation might fail: you can save a backup image on the server and read this file and return it.

If the generation is pretty heavy and doesn't change very much, all the time you catch a cold, everyone cache the resulting file and get this instead if you determine the data hasn't changed. You can use the ARemesal method, which suggests deferring adding an image link until the image is generated and then linking directly to the cached file. (It depends on your specific case, which is best)

0


source







All Articles