I have a form with a single file field:
<form id="myForm" action="/processFile" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile">
</form>
And I want to submit the form via AJAX (using jQuery on the client-side and Node.JS on the server side).
This is what I tried first on the client-side in jQuery (after looking at questions like this one Submit form via AJAX in jQuery):
submitButton.on('click', function(ev) {
$.ajax({
type: "GET",
url: $('#myForm').action
data: { form: $('#myForm').seralize() }
}).done(function(res) {
$('#targetDiv').html(res);
});
});
Sadly, this didn't work because the .seralize() method doesn't work for file inputs.
So I decided that actually posting the form was the best route because it handles the asynchronous messiness of uploading the file to the server. So I tried this:
submitButton.on('click', function(ev) {
$('#myForm').submit(function(err) {
$.ajax({
type: "GET",
url: $('#myForm').action
data: { form: $('#myForm').seralize() }
}).done(function(res) {
$('#targetDiv').html(res);
});
});
});
That is, (1) actually submitting the form, and then (2) making my ajax call in the callback of the form submission.
Sadly, this also doesn't work because submitting the form expects the entire page to reload based on the response from "/processFile".
What I want is (1) to submit the file input as simply as possible through AJAX, and (2) use the response of the URL to inject some partial HTML. It seems like you could hack around this using some iFrame trickery (like this http://www.jainaewen.com/files/javascript/jquery/iframe-post-form.html) but is there a cleaner way that I'm not seeing?