File upload via Jquery ajax in wordpress

HTML View

  <form enctype="multipart/form-data" id="form_data_upload">
  Name:
  <input id="name_name" type="text" name="name_data" >
  Select File:
  <input id="user_file" type="file" name="file_name_data" multiple >
  <br><br>
  <button id="save_form" type="button" name="save">Submit</button>
  </form>

JQuery

  jQuery(document).ready(function(){
        jQuery("#save_form").on('click',(function(){
            var u_name = $("#name_name").val();
            var fd = new FormData();
            var file = jQuery(document).find('input[type="file"]');
            var upload_file = file[0].files[0];
            fd.append("file", upload_file);
            fd.append("name", u_name);  
            fd.append('action', 'my_form_action');  

            jQuery.ajax({
                type: 'POST',
                url: ajaxurl,
                data: fd,
                processData: false,
                contentType: false,
                success: function(response){
                    console.log(response);
                }
            });

        }));
    });

PHP

  public function my_form_action(){
        global $wpdb;
        var_dump($_FILES, $_POST);
        exit();
  }
 
 add_action('wp_ajax_my_form_action' , 'my_form_action');
 add_action('wp_ajax_my_form_action_edit', 'my_form_action_edit');

0 Comments

Leave a Comment