96

I try to make ajax script for upload for Symfony 2. Chrome returns this error:

Uncaught TypeError: Illegal invocation jquery.min.js:4

I think it's due to the FormData object not correctly constructed (I try the script with .serialized():

$(document).ready(function() {
  $('#formImage').submit(function(event) {
    event.preventDefault();
    // appel Ajax
    alert("ajax");

    var input = document.getElementById("rasta_blogbundle_imagetype_file");
    console.log(input); 
    var formdata = false;  

    if (window.FormData) {  
        formdata = new FormData();
        console.log('formdata initialized ...');  
    }
    else{
        console.log('formdata not supported');
    }

    formdata.append('name',$('#rasta_blogbundle_imagetype_name').val());
    console.log(formdata);
    formdata.append('file',input);
    formdata.append('_token',$('#rasta_blogbundle_imagetype__token').val());
    console.log(formdata);    
    //alert(DATA);

    if (formdata){  
        $.ajax({
            url: $(this).attr('action'), // le nom du fichier indiqué dans le formulaire
            type: $(this).attr('method'), // la méthode indiquée dans le formulaire (get ou post)
            cache: false,
            //data : $(this).serialize(),
            data: formdata ,
            success: function(data) { // je récupère la réponse du fichier PHP
                $('#myModal').html(data);
                console.log('ok');
            }        
            //return false; //
        }); 
    }
  });
});
Jason
  • 11,263
  • 21
  • 87
  • 181
darkiron
  • 1,174
  • 1
  • 10
  • 20

3 Answers3

273

jQuery tries to transform your FormData object to a string, add this to your $.ajax call:

processData: false,
contentType: false
djangonaut
  • 7,233
  • 5
  • 37
  • 52
4

it occurs sometime when jquery internally not serialize data correctly data to fix it add this.

cache : false,
dataType    : 'json',
processData : false,
user889030
  • 4,353
  • 3
  • 48
  • 51
3

I have solved the issue just by adding following these:

contentType: false,
processData: false,
cache: false,
Ibnul Quayum
  • 119
  • 4