ajax formdata : Illegal invocation

AjaxFile

Ajax Problem Overview


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; //
        }); 
    }
  });
});

Ajax Solutions


Solution 1 - Ajax

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

processData: false,
contentType: false

Solution 2 - Ajax

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

cache : false,
dataType	: 'json',
processData	: false,

Solution 3 - Ajax

I have solved the issue just by adding following these:

contentType: false,
processData: false,
cache: false,

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondarkironView Question on Stackoverflow
Solution 1 - AjaxdjangonautView Answer on Stackoverflow
Solution 2 - Ajaxuser889030View Answer on Stackoverflow
Solution 3 - AjaxIbnul QuayumView Answer on Stackoverflow