Upload csv file from magento 2 admin using ajax method

Step 1: create Form in admin template

<div class="admin__page-section-content" id="warehouse-purchaseorder-mpdal" style="display:none;"> 
    <div class="messages" id="err-msg" style="display:none">    
        <div class="message " id="msgtype">    
            <span id="msg"></span>
        </div>    
    </div>     
    <form id="form-validate_csv" class="form-inline" method="POST" enctype="multipart/form-data" autocomplete="off" data-mage-init='{"validation":{}}' data-hasrequired="<?php echo __('* Required Fields') ?>">    
        <fieldset class="admin__fieldset"  >

            <h3>Please ensure your file type  is .csv</h3>
            <div class="form-group">
                <?php echo $block->getBlockHtml('formkey') ?>

                <label for="upload_csv" class="label"><span><?php echo __('Choose File') ?></span></label>
                <input type="file" name="upload_csv" id="upload_csv" value=""  class="input-file required-entry" data-validate="{required:true}">

            </div>

        </fieldset>
    </form>   

    <span id='ajax_loader1' style='display:none'>
        Loading...      
    </span>

</div>

<script type="text/x-magento-init">
    {
    "*": {
                "Webtechbuzz_ModuleName/js/purchaseOrders": {
                   "purchaseOrdersUrl": "<?php echo $this->getPurchaseOrdersAjaxUrl() ?>"
                 }
         }
    }          
</script>

Step 2: Write javascript for uploading csv file purchaseOrders.js


define(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function (
                $,
                modal
                ) {
            'use strict';
            return function (config) {
                var options = {
                    type: 'popup',
                    responsive: true,
                    innerScroll: true,
                    title: 'Upload CSV',
                    buttons: [{
                            text: $.mage.__('Upload'),
                            class: 'uploadbtmodal',
                            click: function (data) {
                                if ($('#form-validate_csv').valid())
                                {

                                    var formData = new FormData();
                                    
                                    formData.append('file', jQuery('input[type=file]')[0].files[0]);
                                   
  
                                    jQuery('#ajax_loader1').show();
                                    jQuery.ajax({
                                        url: config.purchaseOrdersUrl+"?form_key="+FORM_KEY,
                                        type: 'POST',
                                        data: formData,
                                        processData: false,
                                        contentType: false,
                                        cache: false,
                                        enctype: 'multipart/form-data',
                                        
                                        success: function (data) {
                                            jQuery('#ajax_loader1').hide();
                                            //jQuery('.uploadbtmodal').hide();
                                            console.log(data);
                                            // $("#sale-mpdal").modal("closeModal");
                                            jQuery("#err-msg").show();
                                            jQuery("#msgtype").addClass("message-success success");
                                            jQuery("#msg").html("File Uploaded Created");
                                            //location.reload();
                                        },
                                        error: function (result) {
                                            console.log('no response !');
                                        }
                                    });
                                }
                            }
                        },
                        {
                            text: $.mage.__('Clear'),
                            class: 'clear',
                            click: function () {
                                // this.closeModal();
                                $('#form-validate_csv').trigger('reset');
                            }
                        }]
                };
                var popup = modal(options, $('#warehouse-purchaseorder-mpdal'));
                $("#uploadpurchasebutton").on('click', function () {
                    $("#warehouse-purchaseorder-mpdal").modal("openModal");

                });
            }
        }
);

Leave a Reply

Your email address will not be published. Required fields are marked *