title: Passing a file input HTML to php with AJAX JavaScript
body: <p>I want pass a file of one form to a php with AJAX JavaScript.</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;div class="imagen bloque"&gt;
     &lt;div class="imagen-prev-texto"&gt;Vista previa&lt;/div&gt;
     &lt;div class="imagen-prev"&gt;&lt;img src="img/stop" alt="" width="200px" height="200px"&gt;&lt;/div&gt;
     &lt;form id="form"&gt;
        &lt;input type="file" id="fileselectInput"&gt;&lt;br&gt;
        &lt;button type="button" onclick="previewIMG()"&gt; Submit &lt;/button&gt;
     &lt;/form&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>PHP subir_img_producto:</p>
  
  <pre><code>&lt;?php
  $allowedExts = array("gif", "jpeg", "jpg", "png");
  $temp = explode(".", $_FILES["file"]["name"]);
  $extension = end($temp);
  if ((($_FILES["file"]["type"] == "image/gif")
  || ($_FILES["file"]["type"] == "image/jpeg")
  || ($_FILES["file"]["type"] == "image/jpg")
  || ($_FILES["file"]["type"] == "image/pjpeg")
  || ($_FILES["file"]["type"] == "image/x-png")
  || ($_FILES["file"]["type"] == "image/png"))
  &amp;&amp; ($_FILES["file"]["size"] &lt; 20000000)
  &amp;&amp; in_array($extension, $allowedExts))
    {
    if ($_FILES["file"]["error"] &gt; 0)
  {
  echo "Code Error: " . $_FILES["file"]["error"] . "&lt;br&gt;"; /
  }
    else
  {
  if (file_exists("tmp/" . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . " already exist in the server. "; 
    }
  else
    {
    $rutafinal ="tmp/".$_FILES["file"]["name"];
    move_uploaded_file($_FILES["file"]["tmp_name"],$rutafinal);
    echo $rutafinal;
    //echo "Stored in: " . "tmp/" . $_FILES["file"]["name"]; 
    }
  }
    }
  else
    {
       echo "no valid file";
    }
  </code></pre>
  
  <p>I try this with JavaScript, but no works</p>
  
  <pre><code>function previewIMG() {
      var formData = new FormData($("#form"));
      alert(formData);
      var url ="subir_img_producto.php";
      if (window.XMLHttpRequest){
          xmlhttp=new XMLHttpRequest();
      }else{
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
  
      var http = new XMLHttpRequest();
      http.open("POST", url, true);
      http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http.setRequestHeader("Content-length", formData.length);
      http.setRequestHeader("Connection", "close");
      http.send(formData);
  
      http.onreadystatechange = function() {
          if(http.readyState == 4 &amp;&amp; http.status == 200) {
                      document.getElementById('cuadroIMG').src=http.responseText;
          }
      }
      }
  </code></pre>
  
  <p>I used a php with a basic form in HTML and it worked perfectly, so the PHP is fine.</p>
  
  <p>I exeute all of this in apache server, XAMPP.</p>
  
  <p>I hope I've put everything you need to help me, I'm not averse been using jQuery but I have no knowledge of jQuery, but will use if necessary.</p>