Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload multiple image upload without submit button using ajax jquery?

How to upload multiple image upload without submit button using ajax jquery?Can someone help my finding out whats wrong?

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">     </script> 

Here is the code

  <body> 
    <input name="files[]" type="file" multiple />
    <input type="hidden" name="hiddenval" id="hiddenval" value="">
    <button id="upload" value="Upload" class="btn btn-success" />
  </body>
</html>

<script>
  $(document).on("click", "#upload", function() {
    var outputdata = [];

    $.ajax({
      url: "upload1.php",
      type: "POST",
       data: new Form(this),
      contentType: false,
      processData: false,
      success: function(files, data, xhr) {
        outputdata.push(files);
        $('#hiddenval').val(outputdata)
      }
    });
  });
</script>
like image 747
think_user Avatar asked Oct 28 '22 21:10

think_user


1 Answers

add id to this input for easier get value.

<input name="files[]" type="file" multiple id="files"/>  

Includes values from this input to data:

$(document).on("click", "#upload", function() {
    var outputdata = [];
    var fileSelect = document.getElementById('files');
    var files = fileSelect.files;
    var formData = new FormData();
    // Loop through each of the selected files.
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        // Check the file type.
        if (!file.type.match('image.*')) {
            continue;
        }
        // Add the file to the request.
        formData.append('photos[]', file, file.name);
    }

    $.ajax({  
        url: "upload1.php",  
        type: "POST",  
        data: formData,  
        contentType: false,  
        processData:false,  
        success: function(files,data,xhr)  
        {           
           outputdata.push(files);
           $('#hiddenval').val(outputdata);
        }  
    }); 
});

Refer: http://blog.teamtreehouse.com/uploading-files-ajax

like image 109
Lý Trung Tín Avatar answered Nov 01 '22 16:11

Lý Trung Tín