I'm using wordpress with ajax in a frontend form and I'd need support for handling and uploading the featured image. My problem is specifically about the featured image. My html is something like:
<form id="msform" action="#" method="post" enctype="multipart/form-data">
//inputs of various nature
<input type="file" name="main_image" id="main_image" multiple="false" value="" accept=".png, .jpg, .jpeg, .gif"/>
<input type="submit" class="submit" value="Publish"/>
</form>
I send data to a php function (following Wordpress methods) through this jquery:
function apfaddpost() {
var formData = $('#msform').serialize();
formData.append('main_image', $('#main_image')[0].files[0]); //here should be the problem
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
data: formData + '&action=apf_addpost', //here I send data to the php function calling the specific action
processData: false,
contentType: false
success: function(data, textStatus, XMLHttpRequest) {
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
My function php is something like
function apf_addpost() {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$file_handler = 'main_image';
$attach_id = media_handle_upload($file_handler,$pid );
update_post_meta($pid,'_thumbnail_id',$attach_id);
}
Important to say: all the other data like title, description, tags are correctly serialized and sent. The problem is for the image. I've tried also to use the $_FILES[]
handler without success and I suppose that my ajax code is not so great then. Can you help me? If you have any other workaround for this issue please share! Thanks in advance.
[SOLVED] EDIT
Thanks to the answers below I've just changed my ajax into
function apfaddpost() {
var fd = new FormData($('#msform')[0]);
fd.append( "main_image", $('#main_image')[0].files[0]);
fd.append( "action", 'apf_addpost');
//Append here your necessary data
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
data: fd,
processData: false,
contentType: false,
success: function(data, textStatus, XMLHttpRequest) {
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
I've discovered that FormData()
allows to serialize files, thing that .serialize()
method doesn't. Known that, it has been simple to move on.
Thanks.