I’ve made a script which uses $.ajax and FormData to pass two form objects to PHP. One form object is a text and the other is a file.
It worked well as a stand-alone script. However, after I added it to WordPress, as a plugin, it keeps giving me "Uncaught TypeError: Illegal invocation"
.
I can’t afford to serialize the formdata, simply because then I won’t be able to pass the file to the callback function in PHP.
JS involving FormData before ajax call:
var fd = new FormData();
var file = jQuery(this).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
This part above is 100% correct.
Ajax call:
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: {
action: 'fiu_upload_file',
security: fiuajax.security,
data: fd,
contentType: false,
processData: false,
},
success: function(response){
var dataObj = jQuery.parseJSON(response);
if(dataObj.message == 'error') {
jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
}
else if(dataObj.message == 'success') {
jQuery('.fiu_file').val('');
}
console.log(response);
}
});
This is incredibly frustrating since it worked perfectly fine outside of WordPress. I’ve tried de-registering WordPress’ jQuery and enqueueing the latest jQuery version, but it made no difference.
To recap:
1) Ajax/jQuery is refusing to pass a form object to PHP
2) Can’t serialize the object because I need to preserve the file object
3) Script works outside of WordPress
4) Tried updating to the newest jQuery version, no change
try this :
php
I managed to do it. The code works on the latest version of WordPress (4.9.4)
First of all, I’m using XMLHttpRequest to send the data and not the jQuery ajax. This means that you can adapt it to just pure JS.
Notice the
xhttp.setRequestHeader("enctype","multipart/form-data");
which was essential to pass the FormData using this method.JS:
The PHP part is also extremely useful since it requires the files needed to manipulate the received data with the WP core functions.
Here you will also find the code to upload an attachment using the WP core functions.
PHP:
Thank you.
Works whith any input(one or many simple or multiple), textarea, select in your form (WP 5.0.3)
and php for only the files
I added
and it helps.
Full listing of your code of Ajax call:
here some modified code in case you have multiple data and multiple files