1

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!

2 Answers 2

3

Uploading files in ajax is a bit tricky because it is not possible to upload files using the browser's XMLHttpRequest object so you need to use some kind of Ajax upload plugin.

Also wp_handle_upload() is not what your using in your code its media_handle_sideload()

  • wp_handle_upload() - should be used for file uploads (input file field)
  • media_handle_sideload() - should be used for remote file uploads (input text field)

take a look at this similar question

5
  • Right I included both methods in the post title because I use both. For images I'm using media_handle_sideload so I save the attachment id as post meta but for a specific reason I use media_handle_upload to save the path for mp3 uploads. I just gave an example for the images. Commented Nov 29, 2012 at 13:03
  • Would you mind showing me an example on how to adapt that to my method. I need to use different functions to process different post type edit forms and I'm doing all this from one page. So I don't understand how I can combine my method with jquery form. Hold my hand please. Commented Nov 29, 2012 at 15:19
  • Humm the answer i linked shows an example.
    – Bainternet
    Commented Nov 29, 2012 at 18:06
  • I just don't get how a the form knows to use my_ajax_upload() to process the form. It's not hooked into the process anywhere in your example. How am I designating which function to use on submit because I have three different ones. Commented Nov 30, 2012 at 5:34
  • you do that by using the add_action('wp_ajax_{each_action}... hook
    – Bainternet
    Commented Dec 1, 2012 at 0:02
1

Actually, its very easy to use ajax to upload files into the media library or wherever you want to!

Wordpress has it's own ajax "plugin" so no need for any other.

Just Use:

$ajaxurl = "<?php echo admin_url('admin-ajax.php');? >";

this allows you to build your upload functions in your functions.php file and call them directly with ajax, sending and retrieving data to and from those functions and the page you're on along with whatever else you are doing.

I've built a complete ajax video upload script which displays the video immediately in the page, allows you to grab a frame of that video to use as its image placeholder, uploads that image then uses ffmpeg to convert, resize and watermark the video!

All this is done behind the scene with wonderful ajax!

Here's an example:

                var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
                var formData = new FormData();

                formData.append('$Parent_Post_ID', $Parent_Post_ID;
                formData.append('$thevideo', $thevideo);
                formData.append('action', 'watermark'); // action should be the name of the function you want to call in your functions.php

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data:formData,
                    cache: false,
                    //async: false,
                    processData: false, // Don't process the files
                    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                    success:function(data) {
                        //alert(data);
                        //data can consist of anything you want to retrieve from the process

                        var datarray = data.split(',');

                        $attach_id = datarray[0];
                        $whatever = datarray[1];
                        $whatever = datarray[2];


                        alert('All Done :)');

                    } // END Ajax Success

                }); // END Ajax Request

In your "upload" function you can easily use the following to upload the file and retrieve the attachment id.

$attach_id = media_handle_upload($file_handler,$Parent_Post_ID );

Hope this gets you on the right path :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.