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; // }); } }); });
Solution for error uncaught TypeError: Illegal invocationAdd processData: false, as key/value pair to ajax settings to avoid the error Uncaught TypeError: Illegal invocation while calling ajax on form submit.
Published on Jan 22, 2021 in JavaScript. Last updated on Apr 17, 2022. The error is thrown when calling a function whose this keyword isn't referring to the object where it originally did, i.e. when the "context" of the function is lost.
processData. If set to false it stops jQuery processing any of the data. In other words if processData is false jQuery simply sends whatever you specify as data in an Ajax request without any attempt to modify it by encoding as a query string.
The jQuery Ajax formData is a method to provide form values like text, number, images, and files and upload on the URL sever. The jQuery Ajax formData is a function to create a new object and send multiple files using this object.
jQuery tries to transform your FormData object to a string, add this to your $.ajax call:
processData: false, contentType: false
it occurs sometime when jquery internally not serialize data correctly data to fix it add this.
cache : false, dataType : 'json', processData : false,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With