Question

I'm struggling to figure out how to use wp_handle_upload() with ajax when processing a form. What I'm doing here is using a form to allow users to edit posts from the front end so they can do some things like change the image for a post so we'll start there.

I'm gonna leave out chunks of this function to keep it simple including the error checking.

 // Process the edit form
 add_action('wp_ajax_process_edit_form', 'process_edit_form');  
 function process_edit_form() {

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $image_file = $_POST['imageFile'];
    $image_file_name = $_POST['imageFileName']; 

    $post_to_edit = get_post($_POST['postId']);

    // Set Image File
    if ($image_file["size"] > 0) {
        $cover_art_id = media_handle_sideload( $album_cover, $pid );
        wp_set_object_terms( $cover_art_id, 'cover_art', 'category');
        update_post_meta($pid,'music_art',$cover_art_id);
    } 


 }

And a basic html form

<form enctype="multipart/form-data">
  <input type="file" name="image_file" id="image_file" />
  <input type="submit" value="Save Changes" tabindex="6" id="submit" name="submit" data-id="<?php echo $post->ID; ?>" />
</form>

And now some jquery. Note that the script this jquery has been localized and everything else in the form works correctly using my methods. The only thing that doesn't work is the file upload on submit.

$(document).on("click","#submit", function(e) {
    e.preventDefault();
    $this = $(this);
    postId = $this.data("id");
    imageFile = $this.closest("form").find("#image_file").val();
    if (imageFile != "") {
      imageFileName = $this.closest("form").find("#image_file").val().split('\\').pop();
    } else {
      imageFileName = "none";       
            };    
   data = {
      action: 'process_edit_form',
      postId : postId,
      imageFile : imageFile,
      imageFileName : imageFileName
   };
   $.post(ajaxurl, data, function (response) {
   });
});

I might have made some errors transferring this over but this is basically what I'm doing. So why does this not work? I saw this answer that says I need to use some type of ajax upload plugin but I'd like to do it without and if I don't understand how I'm using them to save the upload as an attachment. Straighten me out!

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top