117

I'm Trying to upload image on with jquery and ajax. But weird thing happened here. In console Log its showing

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

Please tell me what i did wrong here?

JS script

var prosrc=$("#pro_pix img").last().attr("src");
$("#logoform").on('change',function(event){
var postData = new FormData(this);
$("#pro_pix img").last().hide();
$("#pro_pix img").first().show();
event.preventDefault();
$.ajax(
    {
        url : "/function/pro_pic_upload.php",
        type: "POST",
        data : postData,
        success:function(data, textStatus, jqXHR)
        {
        $("#pro_pix img").last().show();
        $("#pro_pix img").first().hide();
        $("#pro_pix h6").text(data);
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //if fails     
        }
    });
});

My HTML Markup

 <div class="row">
    <!-- left column -->
    <div id="pro_pix" class="col-md-4 col-sm-6 col-xs-12">
      <div class="text-center">
        <img src="template/image/725.GIF" class="avatar img-circle img-thumbnail" style="display:none" alt="avatar">
        <img src="<?php echo $rowuser['profile_logo']; ?>" class="avatar img-circle img-thumbnail" alt="avatar">
        <h6>Upload a different photo...</h6>
        <form role="form" id="logoform" enctype="multipart/form-data">
        <input id="logo" name="logo" type="file" class="text-center center-block well well-sm">
        </form>
      </div>
    </div>
  • Look at the first related question: [How to send FormData objects with Ajax-requests in jQuery?](http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery?rq=1). – Felix Kling Aug 19 '14 at 18:39

6 Answers6

229

in order to use formdata with jquery you have to set the correct options

$.ajax({
    url : "/function/pro_pic_upload.php",
    type: "POST",
    data : postData,
    processData: false,
    contentType: false,
    success:function(data, textStatus, jqXHR){
        $("#pro_pix img").last().show();
        $("#pro_pix img").first().hide();
        $("#pro_pix h6").text(data);
    },
    error: function(jqXHR, textStatus, errorThrown){
        //if fails     
    }
});

.ajax reference

processData (default: true)

Type: Boolean

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • I have a confusion. will you please help me? suppose i want to send a file and a string together with a array. Suppose in my script i want to send the image file and a string with username. how to do that? Is it possible to make a json or xml or any other array to hold file and string together? I am beginner. may be this is the silly question. i need your help.. –  Aug 19 '14 at 18:45
  • 1
    just call the append method of the FormData object to add items, ie: `postData.append("name",value);` – Patrick Evans Aug 19 '14 at 18:47
  • Note for complex items like objects, ie: `{cat:"meow",dog:"bark"}`, you have to use JSON.stringify first: `postData.append("name",JSON.stringify(someObject));` and parse the json on the server end – Patrick Evans Aug 19 '14 at 18:51
  • 2
    Do not forget: `cache: false` It gave me problems just now. With it all fixed. – Zri Oct 29 '15 at 08:40
  • Thank you, I've been stuck on this issue for the past hour! – user752746 Jun 12 '16 at 07:24
  • But, I want to use multi-part form data? This is changing my content type and now my backend doesn't know how to parse it? :/ – CaffeinateOften Sep 16 '16 at 19:20
  • @ChrisDillinger, It will use multi-part form data that is the only content type that sends file(s) data over an http request – Patrick Evans Sep 17 '16 at 02:03
  • You're a God ! Thanks :) – FreeKrishna Jan 20 '17 at 11:18
  • It's people like you that seriously helped make my day better. Thank you so much for your help <3 – Teyler Halama Nov 15 '17 at 22:07
48

Add these two parameters in your AJAX to solve your problem:

processData: false,
contentType: false,
Cesare
  • 9,139
  • 16
  • 78
  • 130
  • 1
    Do not forget: `cache: false` It gave me problems just now. With it all fixed. – Zri Oct 29 '15 at 08:41
  • @Zri, what is mean of `cache: false` ? – Fatih Mert Doğancan Jan 24 '16 at 02:36
  • From jQuery documentation: cache (default: true, false for dataType 'script' and 'jsonp') Type: Boolean If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. – Zri Jan 24 '16 at 22:34
  • 2
    @Zri You may be using a `GET` request. The `cache:false` won't work properly for `POST` request. As you mentioned in the above comment, it works only for `HEAD` and `GET` requests. And `FormData` is used to submit a form data which should be a `POST` instead of `GET`. So I suggest you always use POST for submitting form data. – Lucky Feb 19 '16 at 07:37
7

Adding:

processData: false,
contentType: false,

will definitely help with the file, an aside to that is if you are doing any sort of passing errors or success messages back to the page, you will want to use json to make your life easier.

example:

dataType: 'json',

this will help with parsing your responses. Without it, it will throw an error.

modnarrandom
  • 142
  • 1
  • 13
1

You have to set this parameter in the ajax call:

enctype: 'multipart/form-data'
Pang
  • 9,564
  • 146
  • 81
  • 122
Krupal Patel
  • 1,387
  • 3
  • 12
  • 28
0

Or you can try to change:

data : postData,

to

data : postData.entries(),
the_root
  • 329
  • 3
  • 9
-1

Just edit your line:

var postData = new FormData(this);

to:

var postData = new FormData($(this));
elcortegano
  • 2,444
  • 11
  • 40
  • 58
e sadeghi
  • 43
  • 4