1

html:

<input id="fileSelect" type="file" name="files[]" multiple="multiple" accept="image/*" />

js:

alert( filesArray );
3 three images.// 
// [object File],[object File],[object File]

// new FormData object.
var formData = new FormData();
formData.append( 'files[]', filesArray );

jQuery.ajax
({
    url: ajaxurl, // uploadfile.php
    type: "POST",
    data:   {
                action: 'auto_post',
                form_data: formData
    },
    processData: false,
    contentType: false,
    success: function( data )
    {
       alert( data );
    },
    error: function( data )
    { }
});

When i don't use:

processData: false,
contentType: false,

I got: (error)

TypeError: 'append' called on an object that does not implement interface FormData.

What to do now? I need the the formData to send to the php server side using ajax.

uploadfile.php

I need to access like this here:

$_FILES["files"]["name"];

Ajax data get here:

// Ajax Funtion.
function aap_auto_post()
{
    echo $_FILES['files']['name'];
    die();
}
add_action( 'wp_ajax_auto_post', 'aap_auto_post' );
add_action( 'wp_ajax_nopriv_auto_post', 'aap_auto_post' );

2 Answers 2

2

All values sent in an ajax request must be appended to the FormData object, not just the files. Also the files have to be added individually.

var formData = new FormData();
for (var i = 0; i < filesArray.length; i++){
    formData.append( 'files[]', filesArray[i]);
}
formData.append( 'action', 'auto_post');
...
data: formData,
Sign up to request clarification or add additional context in comments.

7 Comments

what's this: formData.append( 'action', 'auto_post');
That's the action parameter you're trying to post
getting the same thing: TypeError: 'append' called on an object that does not implement interface FormData.
its in jquery.1.11.js file: ...,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURICo...
|
0

Use the id to select the form like this

$('form#YOUR_FORM_ID').submit(function(e){
 e.preventDefault();   
 var formData = new FormData($(this)[0]);
 $.ajax({
   url: 'YOUR_SERVER_URI',
   type: 'POST',
   data: formData,
   async: true,         
   success: function (data) { 
         alert(data);
   },
   cache: false,
   contentType: false,
   processData: false
   });  
      return false;

});

This will process the $_FILES as well on the server side. Do it as you do it normally.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.