Search code examples
phpajaxformsprototypejsmultipartform-data

Prototype js : input type file is missing on ajax submit


I have create a varien custom form and want to submit the form using prototype ajax.This form contain four fields

two text field and 
two file field.

But when i submit the data using ajax of prototype js the form did not passed two field and on enctype="multipart/form-data" but does not works. Code:

<form action="bt" method="post" enctype="multipart/form-data" name="new-art-upload" id="new-art-upload">
<input type="text" name="fname" value=""   class="input-text required-entry"/>
<input type="text" name="fname" value="" class="input-text required-entry"  />
<input type="file" name="fileone"  class="required-entry"   />
<input type="file" name="filetwo" class="required-entry"   />
<button type="submit" title="<?php echo $this->__('Save The Art') ?>"  class="button newAdd_Sub" onclick="newartUpload.submit(this)"><span><span><?php echo $this->__('Save Art') ?></button>
</form>

Script:

<script>
    var newartUpload=new VarienForm('new-art-upload');
    newartUpload.submit=function(button,url){
    if(this.validator.validate) {
        var form=this.form;
        var oldUrl = form.action;
        if (url) {
           form.action = url;
        }
        var e=null;
        try{
          // this.form.submit();
           new Ajax.Request(this.form.action,{
            method:this.form.method,
            parameters:this.form.serialize(),
                    contentType: 'multipart/form-data',

            onSuccess:function(transport){
                var response=transport.responseText.evalJSON(true);

            }.bind(this)
            });


        }catch(e){
        }
        if(e){
            throw e;
        }
    }
    }.bind(newartUpload)
</script>

I guess that it may content type and mostly content type in form/

Main issue is that files input fields are not sended to ajax request


Solution

  • You can't submit a file using Prototype through Ajax, because XMLHttpRequest (the foundation of Ajax) does not work with a multipart form. There are work-arounds, such as using a keyhole iframe to send a normal form request, and using a callback through the iframe to redirect or react the outer page to show that the form completed. The new File interface in modern JS (standardized years after the Prototype Ajax interface was written) now makes it possible to send file data through a JS submission, but this was actively discouraged (and only possible at all in a tiny handful of browsers, not too long ago) so Prototype just drops file inputs from the list of form elements it will serialize.