title: Use jQuery AJAX to upload a file via FormData
body: <p>I want to upload a single file using just jQuery and then replace the upload form with the output from the PHP script that has processed the file upload.</p>
  
  <p>Currently after I click submit, I receive a blank response from the PHP script. I think it's because the form data (file and upload inputs) is being overwritten by the upload data?</p>
  
  <p>Any help solving this is much appreciated!</p>
  
  <p>Here is my code:</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;div id="container"&gt;
      &lt;form id="form" enctype="multipart/form-data"&gt;
          &lt;input name="file" type="file"&gt;
          &lt;input type="hidden" name="upload"&gt;
      &lt;/form&gt;
      &lt;a href="javascript:void(0)" onclick="uploadData($('#form').serialize(), 'upload.php', '#container'); return false;"&gt;Upload &amp;gt;&lt;/a&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>JavaScript</strong></p>
  
  <pre><code>function uploadData(data, url, container) {
  
      var formData = new FormData($(data)[0]);
  
      $.ajax({
          type: 'POST',
          url: url,
          data: formData,
          cache: false,
          contentType: false,
          processData: false,
          success: function(response) {
              $(container).html(response);
          },
          error: function() {
              alert('Error!');
          },
      });
  
      return false;
  };
  </code></pre>
  
  <p><strong>PHP</strong></p>
  
  <pre><code>if (isset($_POST['upload'])) {
  
      // check the file has been uploaded
      if (isset($_FILES['file'])) {
  
          // check if there was an error uploading the file
          if ($_FILES['file']['error'] &gt; 0) {
  
              // display error
              echo 'Error: ' . $_FILES['file']['error'];
          } else {
  
              // move and store file (overwrite if it already exists)
              $fileName = '/upload/' . $_FILES['file']['name'];
              move_uploaded_file($_FILES['file']['tmp_name'], $fileName);
  
              echo 'File uploaded successfully';
          }
      } else {
  
          die ('Error: No file selected for upload');
      }
  
  }
  </code></pre>