so I'm trying to upload files via a form sent using AJAX, except $_POST
returns an empty array (so does $_FILES
) - though I'm not sure why. Here is the top of my form:
HTML - generated from PHP (inside WP function)
$html .= '<form method="post" class="form-horizontal" id="product-slides-form" enctype="multipart/form-data">';
AJAX
//edit product gallery
$('#update-product-gallery').on('click', function()
{
var product_id = $(this).data('id'),
slides_form = $('#product-slides-form'),
slides_form_data = new FormData(slides_form[0]);
//create array of slides
var slides = {},
counter = 0;
$.each(slides_form.find('input'), function(j, v)
{
if ($(this)[0].files) {
$.each($(this)[0].files, function(i, files)
{
slides_form_data.append('slides-'+ counter, files);
counter++;
})
}
});
//add slideshow data
slides_form_data.append('slides', JSON.stringify(slides));
slides_form_data.append('product-id', product_id);
var slides_data = {};
slides_data['product_id'] = product_id;
slides_form_data.forEach(function(val, key)
{
slides_data[key] = val
});
//if I change data: to below test FormData than it works
var test = new FormData();
test.append('me', 1);
$.ajax({
data: slides_data,
dataType: 'text',
type: 'post',
url: PLUGIN_ROOT+ 'admin/inc/scripts/add-product-slides.php',
cache: false,
contentType: false,
processData: false,
success: function(res) {console.log(res)},
error: function(res) {$.fn.showPopup(2, 'Something went wrong. Please try again.', res)}
})
});
and my script just var_dumps $_POST
+ $_FILES
for now
I console.log'd the FormData using this:
// Display the key/value pairs
for (var pair of slides_data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
and it returns the correct data, so I'm really not sure why my script doesn't get the $_POST
data? Am I missing something really obvious?
(if more code is needed - comment and I'll add more)