0

I'm trying to save the attachment file in my custom module using $.ajax({}) request. But it's not working for me. For these, I tried the below code.

In cart page having below code.

<dl class="item-options">
    <dt>
        <span>Add File to Item</span>
    </dt>
    <dd>
        <?php
            $uName = "itemUploadFile_" . $itemId . "_" . "[]";
            $id = "upload_" . $quote_id . "_" . $itemId;
        ?>
        <input id="<?php echo $id; ?>"  name="<?php echo $uName ?>" multiple="" type="file" class="input-text"/>
    </dd>
</dl>

And javascript code is below

<script type="text/javascript">
    require([
        'jquery',
        'domReady!'
    ], function ($) {
         $("#<?php echo $id ?>").change(function(e) {
            let itemId = "<?php echo $itemId ?>";
            let quote_id = "<?php echo $item->getQuoteId(); ?>";
            const _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png", ".pdf", ".doc", "docx"];
            //console.log(e.target.files[j]);
            if (e.target.files.length > 0) {
                for (let j=0; j< e.target.files.length; j++){
                    let fileEx = e.target.files[j].name.split(".");
                    let fileExtension = "." + fileEx[1];
                    if (_validFileExtensions.indexOf(fileExtension.toLowerCase()) > -1) {
                        //let output = JSON.parse(e.target.files[j]);
                        //console.log(output);
                        $.ajax({
                            url: "<?php echo $block->getBaseUrl() . 'test/index/savefile' ?>",
                            method:'POST',
                            dataType:"json",
                            showLoader:true,
                            data: {quote_id: quote_id, quote_item_id: itemId,size: e.target.files[j].size,fileName: e.target.files[j].name},
                            success: function (response) {
                               console.log(response['result']);
                            },
                            error:function (jqXHR, exception) {
                                let msg = '';
                                if (jqXHR.status === 0) {
                                    msg = 'Not connect.\n Verify Network.';
                                } else if (jqXHR.status === 404) {
                                    msg = 'Requested page not found. [404]';
                                } else if (jqXHR.status === 500) {
                                    msg = 'Internal Server Error [500].';
                                } else if (exception === 'parsererror') {
                                    msg = 'Requested JSON parse failed.';
                                } else if (exception === 'timeout') {
                                    msg = 'Time out error.';
                                } else if (exception === 'abort') {
                                    msg = 'Ajax request aborted.';
                                } else {
                                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                                }
                                console.log(msg);
                            }
                        });
                    } else {
                        alert("Sorry, " + e.target.files[j].name + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                        this.value = "";
                        return false;
                    }
                }
            }
        });
    });
</script>

When I send file data using e.target.files[j] it's not working for me.

Can you please suggest us how can I send attachment file details to ajax request?

1
  • Please mention your error log here. Nov 11, 2019 at 11:40

1 Answer 1

0

Finally solved my self by adding below code.

<script type="text/javascript">
    require([
        'jquery',
        'domReady!'
    ], function($,){

         $("#<?php echo $id ?>").change(function(e) {
            let itemId = "<?php echo $itemId ?>";
            let quote_id = "<?php echo $item->getQuoteId(); ?>";
            const _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png", ".pdf", ".doc", "docx"];


            if (e.target.files.length > 0) {
                let countVal = e.target.files.length - 1;
                for ( let j=0; j< e.target.files.length; j++){
                    let fileEx = e.target.files[j].name.split(".");
                    let fileExtension = "." + fileEx[1];
                    if (_validFileExtensions.indexOf(fileExtension.toLowerCase()) > -1) {
                        try{
                            if(countVal === j) {
                                let fd = new FormData();
                                //let names = [];
                                let file_data = $('#<?php echo $id ?>')[0].files;
                                for (let i = 0; i < file_data.length; i++) {
                                    fd.append("file[]", file_data[i]);
                                }
                                //fd.append('file[]', names);
                                fd.append('quote_id', quote_id);
                                fd.append('quote_item_id', itemId);

                                $.ajax({
                                    url: '<?php echo $block->getBaseUrl() . 'test/index/savefile/' ?>',
                                    type: 'post',
                                    data: fd,
                                    contentType: false,
                                    processData: false,
                                    showLoader: true,
                                    success: function (response) {
                                        let data = $.parseJSON(response);
                                        alert(data.result);
                                    },
                                    error: function (response) {
                                        alert('error : ' + JSON.stringify(response));
                                        this.value = "";
                                        return false;
                                    }
                                });
                            }
                        }catch(err) {
                            alert(err.message);
                            this.value = "";
                            return false;
                        }

                    } else {
                        alert("Sorry, " + e.target.files[j].name + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                        this.value = "";
                        return false;
                    }
                }
            }

        });

        $('body').on('click','.quotation_delete',function(e){
            let fileId = $(this).data("id");
            alert(fileId);
        });

    });

</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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