3

I use to work with the submit(callback) jQuery method, in the callback i serialize my form and do an ajax post call.

But this time, i need to upload a file, and this method desn't seems to work, so i try to directly submit the form with the submit() jQuery method, but i am not able to avoid the redirection, i am however calling e.preventDefault(); before:

$('form.input.upload').change(function(e) {
  e.preventDefault();
  $('form.example').submit();
});
imulsion
  • 8,820
  • 20
  • 54
  • 84
Ludo
  • 5,060
  • 15
  • 53
  • 85
  • @apsillers serialize doesn't serialize file type inputs. He'll need to use a separate jQuery plugin for that, or submit the form to a hidden iframe (which won't be as nice, but it gets the job done pretty well for small uploads). – Paul May 09 '13 at 16:30
  • HTML form submission requires redirection. Your intuition to use Ajax is correct -- however, `.serialize` does not handle file data for ``, so you'll need to collect that yourself using a `FileReader`. – apsillers May 09 '13 at 16:30
  • 1
    possible duplicate of [How can I upload files asynchronously with jQuery?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – apsillers May 09 '13 at 16:36
  • [this post](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) has a similar question, and several possible solutions. See if that suits your needs :) – jvilhena May 09 '13 at 16:31

1 Answers1

0

You have to do preventDefault in the onsubmit event of the <form>, not in the onchange event of the <input>:

$("form.example").on("submit", function (e) {
  // preventing browser's native form submit
  e.preventDefault();
});

$("form.example input.upload").on("change", function (e) {
  // auto-submit if input.upload changed
  $("form.example").submit();
});

Update: Before my edit I wasn't exactly correct. The onsubmit event will be fired by clicking on an <input type="submit"> or by pressing Enter in any focused <input>. But: the event is not triggered if you call the submit() function programmatically.

And well, thinking deeper, your real problem - the file uploading - is a bit harder than my answer. The by the comment linked question has a very good answer to this ;)

metadings
  • 3,798
  • 2
  • 28
  • 37