Steve Kim
Steve Kim

Reputation: 5611

jQuery file Upload and ajax

So, I have the following form and js/php:

php

 <form enctype="multipart/form-data">
    <input id="fileupload"  type="file" name="files[]" class="files " onChange="UploadImage" accept='image/*'/>
    <input type="button" class="submit_form" value="submit">    
</form>

<?php 
   add_action( 'wp_ajax_UploadImage', 'UploadImage' );
   function UploadImage()
   {
     $upload_dir = wp_upload_dir();
     $files = $_FILES['files']; 
   //Some function
   }
?>

JS

function UploadImage(e)
{
jQuery('#fileupload').fileupload({
    url: upload_image.ajax_url,
});

if(jQuery('#fileupload')) {
    var form = document.forms.namedItem("upload_video"); 
    var formdata = new FormData(form); 
    formdata.append('action', 'UploadImage');
    jQuery.ajax({           
        success : function(data){                   
                alert('sddsf');
            }
    })
}
};

As you can see from here, when an image is selected using Blueimp jQuery File upload (which the js is not properly written), I want the image file to be handled by the php function.

In other words, the js is not correctly written and I am not sure how to initiate the plugin then when the image is selected, it is processed by the php function via ajax (meaning, how do I parse the file info to php function via ajax?)

Upvotes: 1

Views: 1093

Answers (1)

Lucas Pottersky
Lucas Pottersky

Reputation: 1919

Don't use $.ajax directly. The plugin already does that behind the scenes.

Here's a working example, based on your code, but adapted to run on JSFiddle:

$(document).ready(function(){
    var url = '/echo/json/';
    var formdata = {json: JSON.stringify({field1: 'value1'})};

    jQuery('#fileupload').fileupload({
        url: url,
        formData : formdata,        
        dataType: 'json',
        type: "POST",
        contentType:false,
        processData:false,
        success : function(data){                   
            alert('success...');
            console.dir(data);
        }
    });       
});

Demo: http://jsfiddle.net/pottersky/8usb1sn3/3/

Upvotes: 1

Related Questions