1

I have created a admin template page in magento. ON this page I created a form to browse a csv file and on click submit button I want to send this via ajax to a controller action and there I want to get csv data and insert into custom table.

Below is my code :

<input type="file" name="file" id="file" />
<button name="submit" id="import_button" value="" type="submit" onclick="importData()" >Submit</button>

and ajax is here :

function importData()
{
    var file = jQuery('input[type=file]').prop("files")[0];
        ajaxBlockUrl = '<?php echo $this->getUrl('*\/*\/import') ?>';
        new Ajax.Request(ajaxBlockUrl, {
            method: 'POST',
            parameters: {isAjax: 'true', form_key: FORM_KEY, file : file},
            onSuccess: function (response)
            {
                // success
            }
        });

}

and my controller action :

// how to I get file here
$_FILES['file']['name'];
$file = $this->getRequest()->getParam('file');

My ajax calls successfully controller action but How do I get file here and read data from it?

  • you can not submit file in normal ajax call – Minesh Patel Dec 6 '16 at 6:59
  • Please post an alternative, How will do this ? – Vinaya Maheshwari Dec 6 '16 at 7:01
  • @VinayaMaheshwari working on admin-end or frontend? – Qaisar Satti Dec 6 '16 at 7:02
  • use FormData to send input type file using ajax – Minesh Patel Dec 6 '16 at 7:02
  • @QaisarSatti, I amworking on admin page, I have created a menu in admin and in controller indexAction load template file there. – Vinaya Maheshwari Dec 6 '16 at 7:05
4

your form phtml

<div class="content-header">
    <table cellspacing="0" class="grid-header">
        <tr>
            <td><h3><?php echo $this->__('Import Tracking Number')?></h3></td>
            <td class="a-right">
                <button onclick="editForm.submit()" class="scalable save" type="button"><span>Import</span></button>
            </td>
        </tr>
    </table>
</div>
<div class="entry-edit">
    <form id="edit_form" name="edit_form" method="post" action="<?php echo $this->getUrl('*/*/import')?>" enctype="multipart/form-data">
        <input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
        <div class="entry-edit-head">
        <h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('Import CSV File ')?></h4>
        </div>
        <fieldset id="my-fieldset">
            <table cellspacing="0" class="form-list">
                <tr>
                    <td class="label"><?php echo $this->__('Add CSV File to Import')?> <span class="required">*</span></td>
                    <td class="input-ele"><input type="file" class="input-text required-entry" name="csv" />
                    </td>
                </tr>
            </table>
        </fieldset>
    </form>
</div>
<script type="text/javascript">
    var editForm = new varienForm('edit_form');
</script>

Controller code

 public function importAction()
  {

      $File=$_FILES['csv']['name'];
      $_FILES['csv']['type'];
     $mimes = array('application/vnd.ms-excel','application/octet-stream','text/plain','text/csv','text/tsv');
     if(in_array($_FILES['csv']['type'],$mimes)){
       $absolute_path = Mage::getBaseDir('media') . DS .('massorderprocessing');
 $relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
        // File Upload
        $files = $_FILES['csv']['name'];

                  if(file_exists($absolute_path.DS.$files))
                 {
                       $var = rand(0,99);
                       $files = $var.'_'.$files;
                  }
                  $uploader = new Varien_File_Uploader('csv');
                  $uploader->setAllowRenameFiles(false);
                 $uploader->setFilesDispersion(false);

                   $uploader->save($absolute_path, $files);

      $csvObject = new Varien_File_Csv();
      $data=$csvObject->getData($absolute_path.'/'.$files);

      foreach($data as $dat)
      {
           //do your logic here
      }

  }
  • Trying your code, will let you know if it work. – Vinaya Maheshwari Dec 6 '16 at 7:37
  • This code uploaded file successfully, but unable to read data from CSV. If my column name is Import Area then How to read its value in loop? – Vinaya Maheshwari Dec 6 '16 at 7:42
  • @VinayaMaheshwari that depend on your csv file $dat[0] for first column value $dat[2] for second and goes on. – Qaisar Satti Dec 6 '16 at 7:44
  • When I log $data into log file it return me unreadable data like PK!A7‚Ïr[Content_Types].xml ¢( ¬”ËnÂ0E÷•ú‘·Ub袪*‹>–-ôL<$Žmy. – Vinaya Maheshwari Dec 6 '16 at 9:12
  • 1
    I tried with another file and now getting the result, Thank you for your post. – Vinaya Maheshwari Dec 6 '16 at 9:22
0

Try below and let me know if it works. i have not checked code

function importData()
{
    var file = jQuery('input[type=file]').prop("files")[0];
    var formData = new FormData(file);
    formData.append("isAjax", true);
    formData.append("form_key", FORM_KEY);
        ajaxBlockUrl = '<?php echo $this->getUrl('*\/*\/import') ?>';
        new Ajax.Request(ajaxBlockUrl, {
            method: 'POST',
            parameters: {formData},
            onSuccess: function (response)
            {
                // success
            }
        });

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.