views:

156

answers:

1

I wanted to find a way to upload a single file*, in the background, have it start automatically after file selection, and not require a flash uploader, so I am trying to use two great mechanisms (jQuery.Form and JQuery MultiFile) together. I haven't succeeded, but I'm pretty sure it's because I'm missing something fundamental.

Just using MultiFile, I define the form as follows...

<form id="photoForm" action="image.php" method="post" enctype="multipart/form-data">

The file input button is defined as...

<input id="photoButton" "name="sourceFile" class="photoButton max-1 accept-jpg" type="file">

And the Javascript is...

$('#photoButton').MultiFile({
    afterFileSelect: function(){
         document.getElementById("photoForm").submit();
    }
});

This works perfectly. As soon as the user selects a single file, MultiFile submits the form to the server.


If instead of using MultiFile, as shown above, let's say I include a Submit button along with the JQuery Form plugin defined as follows...

 var options = {
  success: respondToUpload
 }; 

 $('#photoForm').ajaxForm(options);

... this also works perfectly. When the Submit button is clicked, the form is uploaded in the background.


What I don't know how to do is get these two to work together. If I use Javascript to submit the form (as shown in the MultiFile example above), the form is submitted but the JQuery.Form function is not called, so the form does not get submitted in the background.

I thought that maybe I needed to change the form registration as follows...

$('#photoForm').submit(function() {
 $('#photoForm').ajaxForm(options);
});

...but that didn't solve the problem. The same is true when I tried .ajaxSubmit instead of .ajaxForm.

What am I missing?

  • BTW: I know it might sound strange to use MultiFile for single-file uploads, but the idea is that the number of files will be dynamic based on the user's account. So, I'm starting with one but the number changes depending on conditions.
A: 

The answer turns out to be embarrassingly simple.

Instead of programmatically submitting using...

document.getElementById("photoForm").submit();

... I used...

$("#photoForm").submit();

Also, since I only need to upload multiple files on occasion, I used a simpler technique...

1) The form is the same as my original...

<form id="photoForm" action="image.php" method="post" enctype="multipart/form-data">

2) The file input field is basically the same...

<input id="photoFile" "name="sourceFile" style="cursor:pointer;" type="file">

3) If the file input field changes, submit is executed...

$("#photoFile").change(function() {
    $("#photoForm").submit();
});

4) The AjaxForm listener does its thing...

var options = {
    success: respondToUpload
}; 
$('#photoForm').ajaxForm(options);
Alan Neal