How to update div with image in Django?

Below is the matplotlib code that generates a scatter plot as an answer.

def plot(request): r = mlab.csv2rec('data.csv') fig = Figure(figsize=(6,6)) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ax.grid(True,linestyle='-',color='gray') ax.scatter(rx,ry); response=django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response 

I would like to update the div tag in the template using jquery ajax. Below is the jquery code that listens for the sumbit button of the form and updates the div with success.

 <script type="text/javascript" charset="utf-8"> $(function() { $('#plot').submit(function() { jQuery.ajax({ url: this.action, timeout: 2000, aysnc: true, error: function() { console.log("Failed to submit"); }, success: function(r) { $('#plotarea').html(r); } }) return false; }) }) </script> 

But when I click the submit button, the image displays spam instead of the image.

Can any authority direct me to how I could display the image from the answer?

Thanks in advance.

+1
source share
1 answer

It does not work, because plot() outputs the raw image data (with headers), and you assign it directly to the contentarea ( .html() ) div. When url returns image data directly, it should be used as the src attribute of the <img> .

If you do not want to reverse engineer the workflow, you can try base64 to encode the string and use this method: http://www.websiteoptimization.com/speed/tweak/inline-images/ p>

i.e. something like $('#image').attr('src', 'data:image/png;base64,' + r); in your challenge of success.

0
source

All Articles