1

How to pass formData array to php load file. How to pass all file input as array or iterate it ?

$(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' class='file' type='file' /> <br> <input type='button' class='es' name='es' value='Upload This File' />");
    });

    $('.es').click(function (e) {
        e.preventDefault();

        var form = $('.form');
        var formData = new FormData(form);

//                                             |        |
        formData.append('file', $('.file')[0].files[0]);


        $.ajax({
            url: 'lib/upload.php',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            cache: false,
            success: function (data) {
                $('#here').html(data);
            }
        });
    });
});

And html (php) file :

<form id="form" action="" enctype="multipart/form-data" method="post">
    <input name="file[]" class="file" type="file" />
    <input type="button" name="es" class="es" value="Upload This File" />
    <br><br>
    <button class="add_more">Add More Files</button>
</form>

How to pass all file input as array?

sr9yar
  • 4,072
  • 4
  • 49
  • 54

1 Answers1

0

First of all you don't have multiple attribute on the file input and u are selecting the form using class in js but instead of class, u have id on your form tag.

<form id="form" action="" enctype="multipart/form-data" method="post">
    <input name="file[]" multiple class="file" type="file" />
    <input type="button" name="es" class="es" value="Upload This File" />
    <br><br>
    <button class="add_more">Add More Files</button>
</form>

and second is that when the file input is present inside the form then, the FormData created for that form will already contain all the data including files so you don't have to manually push it. So just send it like below.

$(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' class='file' type='file' /> <br> <input type='button' class='es' name='es' value='Upload This File' />");
    });

    $('.es').click(function (e) {
        e.preventDefault();

        var form = $('#form');
        var formData = new FormData(form[0]);    

        $.ajax({
            url: 'lib/upload.php',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            cache: false,
            success: function (data) {
                $('#here').html(data);
            }
        });
    });
});
Shridhar Sharma
  • 2,265
  • 1
  • 8
  • 13