Submit multiple files via ajax form in WordPress

To send multiple files, html will look like this:

<div class="file-upload"> 
     <label> 
          <input type="file" name="mail_file[]" multiple="multiple" onchange="GetFileName();" id="uploaded-file"> 
          <span>Attach files</span> 
    </label>
</div>
<div id="file-name"></div>

Input can be hidden using css, and the "Attach files" button can be styled:

.file-upload input[type=file] {
  display: none;
}
.file-upload span {
  background-image: url('path to your file upload icon');
  background-size: .875rem 1.5rem;
  background-repeat: no-repeat;
  background-position: 1.25rem center;
  display: inline-block;
  border: 1px solid #333232;
  cursor: pointer;
  padding: 1.1875rem 1.5rem 1.1875rem 3.3125rem;
  font-weight: 400;
}

We’ll write a function so that the user sees a list of added files:

function GetFileName () {

    var file = document.getElementById ('uploaded-file').value;

    var files = document.getElementById ('uploaded-file').files;
    var html = "";
    for (index = 0; index < files.length; ++index) {
        //console.log(files[index].name);
        html  += '<div class="inner-file d-flex"><div class="file-icon"></div><span>' + files[index].name+'</span></div>';
    }

    document.getElementById ('file-name').innerHTML = html;

}

After. as the user clicks the form submit button, the JS script will collect all form data, including files, and send them to the server:

<script>

    jQuery(document).ready(function($){
        var form = $(".form");

        form.on("submit", function (event) {
            event.preventDefault();
            var vanilaForm = this;
            var form = $(vanilaForm);

            var way = form.data('action') || "ajax_form";

            var formData = new FormData(vanilaForm);
            formData.append("action", way);

            $.ajax({
                url: "/wp-admin/admin-ajax.php",
                data: formData,
                type: 'POST',
                dataType: "json",
                cache: false,
                contentType: false, 
                processData: false,
                success: PlaceResponse,
                error: function(){}
            });
        });

        function PlaceResponse(response){

            if(response.type === 'success') {
                form.html('<h3>Thanks! Your letter has been sent.</h3>');
            } else {
                form.html('<h3>Error! Your letter has not been sent.</h3>');
            }
        }
    });

</script>

After submitting the form, the files are transferred to the PHP form data handler and sent by e-mail:

add_action( 'wp_ajax_nopriv_ajax_form', 'ajax_form' );
add_action( 'wp_ajax_ajax_form', 'ajax_form' );

function ajax_form() {

    $_POST = wp_unslash($_POST);
    $msg = '';

    $msg .= "<b>Email:</b> {$_POST['client-email']}";


    $cnt = count($_FILES['mail_file']['name']);
    $attachments = array();
    if($cnt > 0) {
        for($i = 0; $i < $cnt; ++$i) {
            $file_dir = WP_CONTENT_DIR . "/uploads/".$_FILES['mail_file']['name'][$i];
            move_uploaded_file ($_FILES['mail_file']['tmp_name'][$i],$file_dir);
            $attachments[$i] = $file_dir;
        }
    }

    $thm = 'Request from the site '.get_bloginfo('name');
    $thm = "=?utf-8?b?" . base64_encode( $thm ) . "?=";

    $mail_to = 'testmail@test.com';
    $headers = "Content-Type: text/html; charset=utf-8\n";

// We send a mail message
    $mail_1 = wp_mail( $mail_to, $thm, $msg, $headers,  $attachments );

    if ($mail_1) {
        $arr      = array( 'type' => 'success' );
        $response = json_encode( $arr );

    } else {
        $arr      = array(
            'type' => 'error'
        );
        $response = json_encode( $arr );
    }

    foreach ($attachments as $attachment) {
        unlink($attachment);
    }

// Message about the result of sending mail
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
        echo $response;
        wp_die();
    }
}

Updated: 17.04.2020

Did this article help you? Rate it!
(1 votes, average: 5.00 out of 5)
Loading...

Support on Patreon https://www.patreon.com/processby

Leave a Reply

Your email address will not be published. Required fields are marked *

Contacts

E-mail: processby@gmail.com
Skype: inprocess.by
Belarus, Grodno

Send message