Here’s an issue I’m having with the .ajaxForm() method of the jQuery Form Plugin. To keep things as understandable as possible, I’ve included most of the salient info in comments with snippets below.
Tested in both Chrome and Firefox, and FORM_2 does actually post to server once I select a file to upload. The problem is that the deal_upload_image_file input is not being included with the post, so the server is not receiving any file.
html:
<!-- FORM_1: Big form, I need to position a file input field in here, -->
<!-- but don't want to submit the file with this form -->
<form id="edit_deal_form">
<div id="upload_image_div">
<!-- Javascript appends the "deal_upload_image_file" input here, then -->
<!-- appends it to FORM_2 when a file is selected -->
</div>
</form>
<!-- FORM_2: A second form that is not visible to user and will -->
<!-- actually do the post of the multipart data -->
<form id="deal_upload_image_form" name="upload_image_form" method="post" enctype="multipart/form-data" action="/upload_image" accept-charset="UTF-8">
</form>
javascript:
$(function() {
add_upload_image_elements();
});
// Add deal_upload_image_file input to FORM_1, and add onChange handler
// to immediately POST to server once a file has been selected
function add_upload_image_elements() {
$('<input>').attr("id", "deal_upload_image_file").attr("name", "deal_upload_image_file").attr("type", "file").appendTo($('#upload_image_div'));
$('#deal_upload_image_file').change(function () {
upload_image();
return false;
});
}
// Move the file input to FORM_2, set up the ajaxForm handler,
// and call submit() on FORM_2.
//
// For clean up, clear the file input field and add it back to FORM_1.
function upload_image() {
// This input field is not getting posted with FORM_2
// even though I append it here!!!
$('#deal_upload_image_file').appendTo($('#deal_upload_image_form'));
$('#deal_upload_image_form').ajaxForm({
success: function(response) {
alert("Success callback");
},
error: function(response) {
alert("Error callback");
}
});
$('#deal_upload_image_form').submit();
// clean up
$('#deal_upload_image_file').remove();
add_upload_image_elements();
}
Thanks!
If you don’t consider old browser compatibility, just use new HTML5 APIs. See this answer: Html 5 File upload