views:

239

answers:

3

I have a form which is loaded via jQuery from the external template file:

$('#imguploadform').html(' ').load('{% url upload_form %}');

In template it looks like this:

<img src="{{ MEDIA_URL }}img/misc/upload.png" alt="Illustration" title="myimage" />
<form id="uploadForm" enctype="multipart/form-data" method="post" action="upload_picture/">
    {{ form.as_ul }}
    <input type="submit" value="Upload" id="uploadImage" />
</form>

I'm trying to upload an image with ajax using jquery form plugin:

var submit_options = {
    target: '#picworks',
        dataType: 'json',
        success: function() { 
        alert('It Works!'); 
    }       
   };

   $('#uploadForm').submit(function(){
      $(this).ajaxSubmit(submit_options);
      return false;
   });

But then I want to return a json object from server and dynamically load into page an image using it's returned address. I've tried like this:

def upload_picture(request):
    dest = save_original(request.FILES['image'])
    form = UploadImageForm(request.POST, request.FILES)

    res = json.dumps({ 
        "path": dest,
    })

    return HttpResponse(res, mimetype='application/json')

The problem is that I can't catch a json response in javascript, so my browser shows me just an empty page with json dictionary content. What I'm doing wrong?

A: 

Have your success callback take a parameter. That will be the response.

inklesspen
A: 
var submit_options = {
    target: '#picworks',
    dataType: 'json',
    success: function(response) { 
        alert('It Works!');
        window.location.href = response.path;
    }       
};
lawrence
A: 

I solved the problem! The thing is that function which replace form submitting action with an ajax request is called earlier than the form loads from external file. So it should be like this:

$('#imguploadform').html('&nbsp;').load('{% url upload_form %}', 

    function(){
    var submit_options = {
        dataType: 'json',
        success: update_dom
    };

    function update_dom(data) { 
        $('#picworks').html('<img src="' + data.path + '" alt="Illustration" />');
    }

    $('#uploadForm').submit(function(){
        $(this).ajaxSubmit(submit_options);
        return false;
    });

});
Enchantner