D
D
Daniil Vershinin2020-02-21 13:07:13
WordPress
Daniil Vershinin, 2020-02-21 13:07:13

Ajax sending file via Wordpress mail?

How to submit uploaded file <input type="file" name="attach" id="file"> using Ajax.
And how to accept this file to write it to $attachments, for further attachment to email attachments?

add_action('wp_footer', 'my_action_javascript', 99); 
function my_action_javascript() {
  ?>
  <script type="text/javascript" >
  $("#vacancy_form").submit(function(e) {
    e.preventDefault();
    
    var data = new FormData(this);
    
    data.append('action', 'my_action');
    
    $.ajax({
      url : myajax.url,
      type : 'POST',
      processData: false,
      contentType: false,
      data : data,
      success : function (msg){
        alert('Ответ: ' + msg);
      }
    });
    
  });
    
    
  </script>
  <?php
}

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {

$attachment =????;

  
  $project_name = trim($_POST["project_name"]);
  $admin_email  = "[email protected]";//trim($_POST["admin_email"]);
  $form_subject = trim($_POST["form_subject"]);
  
  foreach ( $_POST as $key => $value ) {
    if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
      $message .= "
      " . ( ($c = !$c) ? '<tr>':'<tr style="background-color: #f8f8f8;">' ) . "
        <td style='padding: 10px; border: #e9e9e9 1px solid;'><b>$key</b></td>
        <td style='padding: 10px; border: #e9e9e9 1px solid;'>$value</td>
      </tr>
      ";
    }
  }

  $message = "<table style='width: 100%;'>$message</table>";

  function adopt($text) {
    return '=?UTF-8?B?'.Base64_encode($text).'?=';
  }

  $headers = "MIME-Version: 1.0" . PHP_EOL .
  "Content-Type: text/html; charset=utf-8" . PHP_EOL .
  'From: '.adopt($project_name).' <'.$admin_email.'>' . PHP_EOL .
  'Reply-To: '.$admin_email.'' . PHP_EOL;

  wp_mail($admin_email, adopt($form_subject), $message, $headers, $attachment);
  
  wp_die();
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Adik Izat, 2020-02-21
@JaxAdam

It 's described here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question