title: How to upload multiple files using PHP, jQuery and AJAX
body: <p>I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload. </p>
  
  <p>Here is my HTML form :</p>
  
  <pre><code>&lt;form enctype="multipart/form-data" action="upload.php" method="post"&gt;
      &lt;input name="file[]" type="file" /&gt;
      &lt;button class="add_more"&gt;Add More Files&lt;/button&gt;
      &lt;input type="button" id="upload" value="Upload File" /&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Here is the JavaScript : </p>
  
  <pre><code>$(document).ready(function(){
      $('.add_more').click(function(e){
          e.preventDefault();
          $(this).before("&lt;input name='file[]' type='file' /&gt;");
      });
  });
  </code></pre>
  
  <p>Here is the code for processing file upload : </p>
  
  <pre><code>for($i=0; $i&lt;count($_FILES['file']['name']); $i++){
  $target_path = "uploads/";
  $ext = explode('.', basename( $_FILES['file']['name'][$i]));
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 
  
  if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
      echo "The file has been uploaded successfully &lt;br /&gt;";
  } else{
      echo "There was an error uploading the file, please try again! &lt;br /&gt;";
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Any suggestions on how I should write my '.submit()' function will be really helpful.</p>