0

I'm trying to create a contact form that lets users upload files. This is the PHP code I have:

function ajax_contactform_action_callback() {
 $error = '';
 $status = 'error';
 if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
   $error = 'All fields are required to enter.';
 } else {
   if (!wp_verify_nonce($_POST['_acf_nonce'], $_POST['action'])) {
     $error = 'Verification error, try again.';
   } else {
     $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
     $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
     $subject = 'A messsage from your website\'s contact form';
     $message = stripslashes($_POST['message']);
     $message .= PHP_EOL.PHP_EOL.'IP address: '.$_SERVER['REMOTE_ADDR'];
     $message .= PHP_EOL.'Sender\'s name: '.$name;
     $message .= PHP_EOL.'E-mail address: '.$email; 
     $sendmsg = 'Thanks, for the message. We will respond as soon as possible.';
     $to = get_option('admin_email'); // If you like change this email address
     $header = 'From: '.get_option('blogname').' <info@mymail.com>'.PHP_EOL;
     $header .= 'Reply-To: '.$email.PHP_EOL;

     if ( ! function_exists( 'wp_handle_upload' ) ) {
       require_once( ABSPATH . 'wp-admin/includes/file.php' );
     }
     $uploadedfile       = $_POST['upload'];
     $upload_overrides   = array( 'test_form' => false );
     $movefile           = wp_handle_upload( $uploadedfile, $upload_overrides );
     $attachments = $movefile[ 'upload' ];
     if ( wp_mail($to, $subject, $message, $header, $attachments) ) {
       $status = 'success';
       $error = $sendmsg;
     } else {
       $error = 'Some errors occurred.';
     }
   }
 }
 $resp = array('status' => $status, 'errmessage' => $error);
 header( "Content-Type: application/json" );
 echo json_encode($resp);
 die();
}
add_action( 'wp_ajax_contactform_action', 'ajax_contactform_action_callback' );
add_action( 'wp_ajax_nopriv_contactform_action', 'ajax_contactform_action_callback' );  

and this is the HTML form:

<form id="contactform">
 <p>
 <label for="name">Name</label>
 <input type="text" name="name" id="name" size="30" tabindex="1" />
 </p>
 <p>
 <label for="email">Email address</label>
 <input type="text" name="email" id="email" size="30" tabindex="2" />
 </p>
 <p>
 <label for="message">Message</label>
 <textarea  name="message" id="message" tabindex="3"></textarea>
 </p>
 <p>
 <p>
 <label for="upload">Upload</label>
 <input type="file" name="upload" accept="application/pdf" />
 </p>
 <p>
 <input type="hidden" name="action" value="contactform_action" />
 '.wp_nonce_field('contactform_action', '_acf_nonce', true, false).'
 <input type="button" value="Submit" id="contactbutton" tabindex="4" />
 </p>
 </form>
 <div id="contact-msg"></div>

The form works fine, except that no attachment is sent with the email. What am I doing wrong?

edit: JS code

jQuery(document).ready(function($) {
  $('#contactbutton').click(function() {
    $('#contact-msg').html('<img src="/loading.gif" alt="Loading...">');
    var message = $('#message').val();
    var name = $('#name').val();
    var email = $('#email').val();
    if (!message || !name || !email) {
      $('#contact-msg').html('At least one of the form fields is empty.');
      return false;
    } else {
      $.ajax({
        type: 'POST',
        url: ajax_object.ajax_url,
        data: $('#contactform').serialize(),
        dataType: 'json',
        success: function(response) {
          if (response.status == 'success') {
            $('#contactform')[0].reset();
          }
          $('#contact-msg').html(response.errmessage);
        }
      });
    }
  });
});
  • edit you question to add debugging details idownvotedbecau.se/nodebugging – Kaperto Nov 13 '19 at 10:55
  • Did you try $movefile[ 'file' ] instead of $movefile[ 'upload' ]? see wp_handle_upload source – Samuel Elh Nov 13 '19 at 10:55
  • @SamuelElh yes, it does not make any difference – Nico Vecchio Nov 13 '19 at 11:01
  • Ah, in that case you'll want to check if the file gets uploaded in the first place. Include your JS code so volunteers can replicate your AJAX form. – Samuel Elh Nov 13 '19 at 11:06
  • Your $.ajax parameters won't send the file to the HTTP request. Add/update the following options: data: new FormData($('#contactform')[0]), processData: false, contentType: false, then debug your PHP code if anything doesn't work. – Samuel Elh Nov 14 '19 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.