I’ve got a Django webapp with a sort of newsfeed functionality. Newsfeeds have titles, bodies, and images associated with them. Users have the ability to edit and update their newsfeeds, including adding a new image.
Currently I’m getting all the data for each feed item like so:
var newsfeeds = [];
$('.feed').each( function (index, element) {
var feed_dict = {'title': $(this).children('#title').val(),
'id': $(this).children('#feed_' + index + '_id').val(),
'should_delete': $(this).children('#should_delete').val(),
'subtitle': $(this).children('#subtitle').val(),
'body': $(this).children('#body').val()};
newsfeeds.push(feed_dict);
});
It’s then sent off using $.ajax(). This is working great.
Now I’m working on the image stuff. Each feed has an associated <input type="/> with a unique ID, so I should be able to get each file. The question then is how to send them off in such a way that I can get all the data in Django’s request.POST and request.FILES. I’ve tried using a FormData object in JS like so:
var data = new FormData();
$('.image_input').each(function(index, element) {
data.append('file_' + index, element.files);
});
But this gives me a NS_ERROR_CANNOT_CONVERT_DATA in Firebug.
At this point, I’m pretty lost. Any pointers would be very helpful.
It’s actually impossible to send files over ajax – if you use something like the jquery form plugin to ‘hijack’ your form, it will submit it to an iframe behind the scenes instead of using XHR.
In any case, you should really write your forms in such a way that they work without javascript, then use jquery form to progressively enhance them. Then you won’t even need to worry about this sort of thing.