title: Upload files to attach and then attach them to mail with phpmailer and jquery
body: <p>Well my problem is this:</p>
  
  <p>I want to successfully upload 2 files to my server and then send an email attaching this 2 files. But when i call the jquery function it only send the email before it successfuly upload and i don't get any attach. I want to wait untill the upload it's done and then send the email with the 2 files correctly attached. By the way im using PHPmailer.</p>
  
  <p>I have this html</p>
  
  <pre><code>    &lt;form enctype="multipart/form-data" class="formulario2"&gt;
   &lt;label for="cel" class="control-label"&gt;Presentación Corporativa&lt;/label&gt;
   &lt;div class="controls"&gt;
    &lt;input type="file" name="file_name2" id="presentacion_web"                                                                          class="inputfile"&gt;
    &lt;label for="presentacion_web" class="btn btn-primary"&gt;Elija un Archivo&lt;/label&gt;
    &lt;input id="nombre_archivo2" disabled&gt;
    &lt;div class="messages2"&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;
   &lt;/div&gt; 
  &lt;/form&gt;
  
  
  &lt;form enctype="multipart/form-data" class="formulario"&gt;
   &lt;label for="dni" class="control-label"&gt;Diseño Aprobado&lt;/label&gt;
   &lt;div class="controls"&gt;
    &lt;input type="file" name="file_name1" id="diseno_aprobado_web" class="inputfile"&gt;
    &lt;label for="diseno_aprobado_web" class="btn btn-primary"&gt;Elija un Archivo&lt;/label&gt;
    &lt;input id="nombre_archivo1" disabled&gt;
    &lt;div class="messages"&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;
   &lt;/div&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>this function in jquery:</p>
  
  <pre><code>$var3 = $("#diseno_aprobado_web").val();
  $var6 = $("#presentacion_web").val();
  $var7 = $var3.substring(12);
  $var8 = $var6.substring(12);
  $.when( enviando1(), enviando2() ).then( function(){
          $.ajax({
              type: 'POST',
              data: ('var3='+$var7+'&amp;var6='+$var8),
              url: 'send_mail.php',
              success: function(salida){
                  alert('Mensaje Enviado');
              }
          });
  
  
      }).done( function(){
          console.log( ' Everything was OK!' );
        })
        .fail( function(){
          console.log( 'Something was failed' );
        });
  function enviando1(){
      var formData = new FormData($(".formulario")[0]);
      var message = ""; 
      $.ajax({
          url: 'upload.php',  
          type: 'POST',
          data: formData,
          cache: false,
          contentType: false,
          processData: false,
          beforeSend: function(){
              message = $("&lt;span class='before'&gt;Subiendo el archivo, por favor espere...&lt;/span&gt;");
              showMessage(message); 
          },
          success: function(data){
              message = $("&lt;span class='success'&gt;El archivo ha subido correctamente.&lt;/span&gt;");
              showMessage(message);
          },
          error: function(){
              message = $("&lt;span class='error'&gt;Ha ocurrido un error.&lt;/span&gt;");
              showMessage(message);
          }
      });
  };
      function showMessage(message){
          $(".messages").html("").show();
          $(".messages").html(message);
      }
  function enviando2(){
      var formData2 = new FormData($(".formulario2")[0]);
      var message2 = "";   
      $.ajax({
          url: 'upload2.php',  
          type: 'POST',
          data: formData2,
          cache: false,
          contentType: false,
          processData: false,
          beforeSend: function(){
              message2 = $("&lt;span class='before'&gt;Subiendo el archivo, por favor espere...&lt;/span&gt;");
              showMessage2(message2);        
          },
          success: function(data){
              message2 = $("&lt;span class='success'&gt;El archivo ha subido correctamente.&lt;/span&gt;");
              showMessage2(message2);
          },
          error: function(){
              message2 = $("&lt;span class='error'&gt;Ha ocurrido un error.&lt;/span&gt;");
              showMessage2(message2);
          }
      });
  };
      function showMessage2(message2){
          $(".messages2").html("").show();
          $(".messages2").html(message2);
      }
  </code></pre>
  
  <p>And this php file (send_mail.php) :</p>
  
  <pre><code>    require('phpmailer/class.phpmailer.php');
  $bodytext = "Correct Message";
  
  $email = new PHPMailer();
  $email-&gt;From      = 'test@mydomain.com';
  $email-&gt;FromName  = 'test bot';
  $email-&gt;Subject   = 'New mail from phpmailer';
  $email-&gt;Body      = $bodytext;
  $email-&gt;AddAddress( 'test2@test2.com' );
  
  $file_to_attach1 = 'folder/' . $_POST['var6'];
  $file_to_attach2 = 'folder/' . $_POST['var3'];
  
  $email-&gt;AddAttachment( $file_to_attach1 , $_POST['var6'] );
  $email-&gt;AddAttachment( $file_to_attach2 , $_POST['var3'] );
  
  
        return $email-&gt;Send();
  </code></pre>
  
  <p>I was trying a lot of code and i'm really stuck and frustrated now. Sorry if is something simple but i couldn't get an answer to my problem.</p>
  
  <p>Thanks!</p>
  
  <p>Update1:</p>
  
  <p>I found this in my upload.php, and i think it's the problem:</p>
  
  <pre><code>$file = $_FILES['file_name']['name'];
  if ($file &amp;&amp; move_uploaded_file($_FILES['file_name']['tmp_name'],"folder/".$file))
  {
     sleep(3);
     echo $file;
  }
  </code></pre>
  
  <p>This is returning a success in my ajax after 3 seconds, how i can turn this </p>
  
  <blockquote>
    <p>"sleep(3)"</p>
  </blockquote>
  
  <p>Into the time required to upload the file?.</p>
  
  <p>Update 2:</p>
  
  <p>upload.php</p>
  
  <pre><code>if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
  
  $file = $_FILES['file_name1']['name'];
  
  if(!is_dir("folder")) 
      mkdir("folder", 0777);
  
  if ($file &amp;&amp; move_uploaded_file($_FILES['file_name1']['tmp_name'],"folder/".$file)){
     sleep(3);
     echo $file;
  }}else{    throw new Exception("Error Processing Request", 1);  }
  </code></pre>
  
  <p>upload2.php</p>
  
  <pre><code>if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
  
  $file = $_FILES['file_name2']['name'];
  
  if(!is_dir("folder")) 
      mkdir("folder", 0777);
  
  if ($file &amp;&amp; move_uploaded_file($_FILES['file_name2']['tmp_name'],"folder/".$file))
  {
     sleep(3);
     echo $file;
  }}else{    throw new Exception("Error Processing Request", 1);}
  </code></pre>