Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to an Ajax upload form nested in another form

I have an HTML form to edit the details of a person in a database system I have at my place of work. Part of the form allows the user to upload a picture of the person. However, this is giving me trouble, because I'm trying to make the form more Ajax-y by letting the user upload the picture and see it successfully uploaded before they submit the person's details to be saved. The part that's giving me trouble is that it seems to necessitate a nested form (that is, the upload form inside the details form), like so:

<form name="details">
    <input name="detail1">
    <input name="detail2">
    <form name="pictureupload">
        <input type="file" name="pic">
        <input type="submit" name="upload" value="Upload">
    </form>
    <input type="submit">
</form>

The way I'm hoping to make it work is that the user would fill out the details of the form, select a picture and hit the "Upload" button, then do an AJAX update when the file is uploaded so that they can see the picture before pressing the final "Submit" button.

Is there a good way to have the upload form be "inside" the details form (at least in appearance on the page) but not nested inside the details form in the HTML?

like image 584
Ben Torell Avatar asked Feb 09 '10 15:02

Ben Torell


1 Answers

You aren't allowed to have forms nested inside each other in valid HTML. Also, file uploads through XMLHTTPRequest objects (the most common AJAX technique) don't work in most browsers.

All is not lost, though. For the AJAX uploads, you will need to use an IFRAME, as presented here: http://www.webtoolkit.info/ajax-file-upload.html

The approach I would suggest for the form is to split it into three form elements. You will have a form that holds the fields before the upload form, the upload form, and the form that holds the fields after the upload form. The first form will not have any submit button. The fields in the first form are duplicated in the third form, as hidden inputs. When the last form's submit button is clicked, some javascript will run that will copy the field data from the first form into the third, so it gets submitted with the last form.

For example, your HTML might look like this::

<form name="details1">
    <input id="fake_detail1" name="detail1" type="text"/>
    <input id="fake_detail2" name="detail2" type="text"/>
</form>
<form name="pictureupload">
   <input type="file" name="pic">
   <input type="submit" name="upload" value="Upload">
</form>
<form name="details2">
    <input id="detail1" name="detail1" type="hidden"/>
    <input id="detail2" name="detail2" type="hidden"/>
    <input id="detail3" name="detail3" type="text"/>
    <input type="submit">
</form>
like image 111
pkaeding Avatar answered Oct 13 '22 13:10

pkaeding