Magento – Magento:Upload file in ajax form

ajaxfile uploadformsmagento-1.9

I have a custom frontend form. The form is submitted via ajax. The form has a "type=file" field. I want to save the uploaded file to a folder.How can I do that. Please help..

How is it possible to get the uploaded file in ajax sumbitted form

This is my "type=file" field in phtml.

<div class="input-box">
    <label for="addfile"><?php echo $this->__('Select File(s)');?></label><br />
    <p>Upload any files that are necessary for your order by clicking on the Add File(s) button below.</p>
    <input type="file" class="file" id="attachment" name="attachement" style="display: none;" onchange="fileSelected(this)" value=""/>
    <input type="button" class="button" id="btnAttachment" onclick="openAttachment()" value="Add File(s)"/>
</div>

This is my button field in phtml.(button action is file upload)

<div>
    <input type="button" class="button" id="btnUpload" onclick="callAjax()" value="Upload File(s)"/>
</div>

This is my script

function callAjax(){
    var filename = document.getElementById("filename").innerHTML;//alert(test);
    var companyname = document.getElementById("company").value;
    var name = document.getElementById("f_name").value+" "+document.getElementById("l_name").value;
    var phnumber = document.getElementById("phnmbr").value;
    var email = document.getElementById("email").value;
    var file = document.getElementById("select-file-det").innerHTML;
     jQuery.ajax({
        type    : "POST",
        url     : "<?php echo Mage::getUrl('module/index/action'); ?>",
        data    : ({company: companyname,name: name,phnumber: phnumber,email:email,file: file,filename:filename }),
        dataType: "json",
        complete: function(response) {   
           document.getElementById("success-msg").style.display = "block"; 
           document.getElementById("select-file-form").style.display = "none"; 
           //setTimeout(function() { window.location=window.location;},3000);           
        },
    });
}

Best Answer

You can try:

function callAjax(){

     jQuery.ajax({
        type    : "POST",
        url     : "<?php echo Mage::getUrl('module/index/action'); ?>",
        data: jQuery('form').serialize(),
        success: function (response) {
           document.getElementById("success-msg").style.display = "block"; 
           document.getElementById("select-file-form").style.display = "none";                          
        },
    });
}
Related Topic