$_FILES not working with ajax submit in woocommerce checkout

I am try to upload file on woocommerce checkout page but I am not able to upload file. I have also try to get value using print_r($_FILES) in create_order function in class-wc-checkout.php file but it will return blank array
When I have remove class checkout from checkout form then it will working fine (without ajax submit)

I want to submit form without ajax but I need ajax remain on checkout page because I have add some extra price using ajax (update price without refresh)

Read More

My ajax call to add extra fee.

   jQuery('#PageCount').change(function () {
            var state = jQuery('#PageCount').val();
            var current_price = jQuery('#carttot').val();
        var data = {
            action: 'woocommerce_apply_state',
            security: wc_checkout_params.apply_state_nonce,
            state: state,
            current_price: current_price
          };
        jQuery.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: data,
            success: function (code) {
           console.log(code);
                if (code === '0') {
                 jQuery('body').trigger('update_checkout');
                }
            },
            dataType: 'html'
        });
        return false;
    });

and php code or woocommerce hooks to add extra fee

add_action('wp_ajax_woocommerce_apply_state', 'calculate_per_page', 10);
add_action('wp_ajax_nopriv_woocommerce_apply_state', 'calculate_per_page', 10);

function calculate_per_page() {
    if (isset($_POST['state'])) {
        global $woocommerce;
        $weight = WC()->cart->cart_contents_weight;
        $state = $_POST['state'];
        $current_price = $_POST['current_price'];
               $val =  $current_price * $state -$current_price;
        session_start();
        $_SESSION['val'] = $val;
    }
}

add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');

function woo_add_cart_fee() {
    session_start();
    $extracost = $_SESSION['val'];
    WC()->cart->add_fee('Per page charges:', $extracost);
}

And my function to upload file..

add_action('woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta');
function custom_checkout_field_update_order_meta( $order_id ) {
if ($_FILES['avatar']['name']) {
 if ( ! function_exists( 'wp_handle_upload' ) ) {
                  require_once( ABSPATH . 'wp-admin/includes/file.php' );
               }
               $upload_dir = wp_upload_dir(); 

               $path = $upload_dir['path']; 

              $fileName = $_FILES["avatar"]["name"]; 
              $fileTmpLoc = $_FILES["avatar"]["tmp_name"];
              $pathAndName = $path."/".$fileName;
              $moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
              update_post_meta( $order_id, 'uploaded_file_to_translate', $_FILES['avatar']['name']);

  if ($_POST['billing_output_to_send']) 
    update_post_meta( $order_id, 'How do you want your translation sent to you?', esc_attr(htmlspecialchars($_POST['billing_output_to_send'])));
  if ($_POST['PageCount']) 
    update_post_meta( $order_id, 'How many pages are in your documents?', esc_attr(htmlspecialchars($_POST['PageCount'])));


         } 
}

How it will possible?

Related posts

1 comment

  1. $_FILES you can not get it at woocommerce_checkout_update_order_meta hook because of woocommerce serialize the form and submit form throw ajax,
    as we know that form serialize can not submit files requests. but I have two solutions for doing this may be it work for you.

    1. You can use a plugin woocommerce upload file in the checkout. you can easily find it on google

    But if you want to upload custom files then you can use this

    1. when onchange file fire an ajax and push file array in session when user checkout, get the files from the session and upload to the directory, and then destroy your session.
    $('.fileupload').change(function(e){
        var action = 'update_session_files';
        e.preventDefault();  
      
        var fd = new FormData();
        fd.append('action', action);
        
            var files = $('input[name="file"]')[0].files[0];
        
            fd.append('billing_artist_headshot', files);
           
                 $.ajax({
                   url: my_ajax_object.ajax_url,
                        type: 'post',
                        data: fd,
                        contentType: false,
                        processData: false,
                        success: function(response){
                           
                        },
                    });
                });
    
    

    and ajax action

    add_action( 'wp_ajax_nopriv_update_session_files', 'update_session_function' );
    add_action( 'wp_ajax_update_session_files', 'update_session_function' );
    function update_session_function(){
    session_start();
    
     $_FILES['billing_artist_headshot'];
    // upload your file here with WordPress and get the id.
    }
    

Comments are closed.