views:

54

answers:

1

The following is a matplotlib code that generates a scatter plot in as the response.

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(r.x,r.y);       
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

I would like to update a div tag in the template using jquery ajax. Following is the jquery code that listens to a form sumbit button and updates a div on 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, junk characters are displayed on the div instead of the image.

Could any body guide me on how I could display the image from the response ?

Thanks in advance.

A: 

It's failing because plot() outputs the raw image data (with headers) and you assign it directly to the contentarea (.html()) of the div. When the url returns the image data directly it should be used as the src attribute of an <img> tag instead.

If you don't wish to redesign your workflow you could try base64 encoding the string and use this method: http://www.websiteoptimization.com/speed/tweak/inline-images/

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

kb
I tried doing it. But I got the junk characters withing the div and I could see it only from Firebug.
Rohit Menon